Javascript:检查数字数组中缺少的数字的数量,以使数组连续

Javascript: Check array of numbers for number of missing numbers needed to make the array consecutive

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

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

我的做法:

这是我的代码:

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 来解决这个问题,但它似乎不起作用。我的代码有什么问题,为什么最后一个元素递增计数器变量?

我会通过构建目标数组来实现它,该数组从输入的最小值+1 到最大值-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))