【问题标题】:Algorithm to find 2 consecutive numbers查找2个连续数字的算法
【发布时间】:2021-07-30 06:39:00
【问题描述】:

考虑一个未排序的数字列表,考虑一个算法来测试列表中的所有项目,以检查是否有任何两个连续的数字(即使它们不相邻)。

  • 例如 1:列表 A = [10,7,23,18,45,24]-> 输出:true
    • 输出为 True,因为 23 和 24 是连续数字(甚至不相邻)
  • 例如 2:列表 B = [24,15,18,18,42,22]-> 输出:false
    • 示例 2 的输出为 False,因为没有任何连续的数字。

现在,回答以下问题:

  1. 写一个算法来解决上面的问题?

【问题讨论】:

  • 首先,在此处添加文本,而不是图像。其次,尝试一些东西,如果它不起作用并在这里发布,那么我们可以提供帮助

标签: arrays list sorting numbers


【解决方案1】:

我已经用 Go 语言实现了这个。 find full code here and run

func isConsecutiveAvailable(arr []int) bool{
    // sort the array in increasing order
    sort.Ints(arr)
    
    // loop the array and find if there is a consecutive
    for i:=0; i < len(arr) -1; i++ {
        if arr[i] + 1 == arr[i+1]{
            return true
        }
    }
    
    // return false if loop cant find any consecutive
    return false
}

【讨论】:

    【解决方案2】:

    将列表从低到高排序,然后以 2 个为一组检查以检查连续数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2011-12-18
      相关资源
      最近更新 更多