【问题标题】:Javascript: Check array of numbers for number of missing numbers needed to make the array consecutiveJavascript:检查数字数组以获取使数组连续所需的缺失数字数
【发布时间】:2020-02-19 04:54:42
【问题描述】:

在 Code Signal 上处理一些 Javascript 挑战,我在解决这个问题时遇到了问题:

Ratiorg 从 CodeMaster 那里得到了不同尺寸的雕像作为生日礼物,每个雕像的尺寸都是非负整数。因为他喜欢把事情做得完美,所以他想把它们从小到大排列,这样每个雕像都会比前一个大一倍。他可能需要一些额外的雕像才能做到这一点。帮助他找出所需的最少额外雕像数量。 例子 对于雕像 = [6, 2, 3, 8],输出应为 makeArrayConsecutive2(雕像)= 3。 Ratiorg 需要尺寸为 4、5 和 7 的雕像。

我的做法:

  • 将数组从小到大排序
  • 创建计数器变量以存储丢失数字的数量
  • 遍历数组
  • 从 [i] 元素中减去 [i + 1] 元素
  • 如果等于 1,数字是连续的,如果不是,数字是不连续的(增量计数器变量)
  • 返回计数器变量

这是我的代码:

function makeArrayConsecutive2(statues) {
    // Sorts array numerically smallest to largest
    statues.sort((a, b) => a - b);

    let counter = 0;

    // If array only contains one number return 0
    if(statues.length === 1) {
        return 0;
    }

    /* Iterate through array, subtract the current element from the next element, if it 
       equals 1 the numbers are consecutive, if it doesn't equal one increment the counter 
       variable */
    for(let i = 0; i <= statues.length -1; i++) {
        if(statues[i] !== statues.length -1 && statues[i + 1] - statues[i] != 1) {
           counter++;
        }

       console.log(statues[i]);
       console.log('counter : ' + counter);
    }

    return counter;       
}

statues 包含[5, 4, 6] 时,输出是这样的:

4
counter : 0
5
counter : 0
6
counter : 1

我认为问题是当数组位于最后一个元素上时,在本例中为 6,当该元素不存在时,它会尝试查看 statues[i + 1]。我在 if 语句中添加了statues[i] !== statues.length -1 来解决这个问题,但它似乎不起作用。我的代码有什么问题,为什么最后一个元素会增加计数器变量?

【问题讨论】:

    标签: javascript arrays sorting for-loop off-by-one


    【解决方案1】:

    我会通过构建目标数组来接近它,该数组从输入的 min+1 到 max-1,不包括输入的成员.....

    function missingConseq(input) {
      let min = Math.min.apply(null, input)
      let max = Math.max.apply(null, input)
      let result = []
    
      for (i = min+1; i < max; i++) {
        if (!input.includes(i)) result.push(i)
      }
      return result
    }
    
    let array = [6, 2, 3, 8]
    console.log(missingConseq(array))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-16
      • 2014-04-19
      • 2021-11-16
      • 2021-04-08
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多