【问题标题】:Write a function to determine whether an array contains consecutive numbers for at least N numbers编写一个函数来判断一个数组是否包含至少 N 个数字的连续数字
【发布时间】:2020-04-21 06:46:34
【问题描述】:

我正在尝试编写一个函数来确定一个数组是否包含至少 N 个数字的连续数字。比如输入是[1,5,3,4]3,就变成true,因为数组有3连续的数字,也就是[3,4,5]

这里这个函数需要预先排序,我认为这不是最有说服力的解决方案。有人可以看看并对此进行一些改进吗?

function hasConsecutiveNums(array, N) {
  if (array.length < N) return false;
  if (N === 0) return true;
  const sortedArray = array.slice().sort((a, b) => a - b);
  let count = 0;
  let prev = null;
  for (const num of sortedArray) {
    if (prev && num === prev + 1) {
      count++;
    } else {
      count = 1;
    }
    if (count === N) return true;
    prev = num;
  }

  return false;
}

console.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true
console.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false

【问题讨论】:

  • 我认为如果你想最小化计算复杂度,提前排序正确的方法。可能还有另一种方法,但你的一般策略是我也会使用的方法
  • 是的,我同意CertainPerformance。或者至少我想不出比排序数组更好/更快的解决方案。你的代码看起来很高效:)

标签: javascript arrays algorithm data-structures


【解决方案1】:

首先对数组进行排序还不错,但是您的程序被重复项破坏并为 ([4, 5, 5, 6], 3) 返回 false。这很容易解决。

首先排序需要 O(N log N) 时间。您可以在预期的 O(N) 时间内完成此操作,但该方法更复杂,并且可能只会在输入非常大的情况下更快。

它是这样工作的:

  1. 创建一个不相交的集合数据结构:https://en.wikipedia.org/wiki/Disjoint-set_data_structure
  2. 遍历数组,将您找到的每个唯一整数映射到该结构中的一个集合。
  3. 添加新整数时,如果前后整数存在集合,则将它们与新整数合并。
  4. 完成后,找出最大集合的大小,它代表最大的连续数字序列。

【讨论】:

    【解决方案2】:

    你可以做一些改变

    • undefined 初始化prev(如果添加数字,null 充当数字零),这样可以
    • prev省略检查
    • 将计数检查移到第一个 ifstatement 内,如果找到所需的递增计数,请提前退出。

    function hasConsecutiveNums(array, N) {
      if (array.length < N) return false;
      if (N === 0) return true;
      const sortedArray = array.slice().sort((a, b) => a - b);
      let count = 0;
      let prev = undefined;
      for (const num of sortedArray) {
        if (num === prev + 1) {
          if (++count === N) return true;
        } else {
          count = 1;
        }        
        prev = num;
      }
      return false;
    }
    
    console.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true
    console.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 2014-06-18
      • 2018-11-19
      • 2014-01-22
      • 1970-01-01
      相关资源
      最近更新 更多