gpt4 book ai didi

javascript - 从数组中获取缺失元素的数量

转载 作者:行者123 更新时间:2023-11-29 16:31:31 25 4
gpt4 key购买 nike

我正在尝试解决任务,从数组中获取缺失元素的数量。例如,如果给定数组 [1,3,6],缺失元素的数量为 3 (2,4,5)。但是某处代码出错,系统不接受该代码。尝试了一些方法,可惜都没有用。

function arr(x){
let y = [];
for (let i = x[0]; i <= x[x.length-1]; i++){
y.push(i);
}
return y.length-x.length;
}
let m = arr([1,2,3,4,5,6]);
console.log(m);

或者...

function arr(x){
let y = [];
for (let i = 0; i < x.length; i++){
for (let j = 0; j < i; j++){
if (x[i] == x[j]){
x.splice(i,1);
i--;
}
}
}
console.log(x);
for (let i = x[0]; i <= x[x.length-1]; i++){
y.push(i);
}
console.log(y);
return y.length-x.length;
}
let l = arr([1,3,2,4,9]);
console.log(l);

我也试过对数组进行排序,但是没有任何变化

最佳答案

老实说,您实际上并不需要 for 循环。我认为你可以通过检查数组的最大数、最小数和长度来计算 nr。

这对你也有用吗?

const source = [1,3,6];

/**
* @method nrOfMissedItems
* @param {Array<Number>} an array containing only numbers
* @returns -Infinity when the parameter arr is null or undefined, otherwise number of non-mentioned numbers, ie [5,5] returns 0, [1,1,1,3] returns 1
* When the array contains non-numbers it will return NaN
*/
function nrOfMissedItems( arr ) {
const noDuplicates = [...new Set(arr)];
const highestNumber = Math.max( ...noDuplicates );
const lowestNumber = Math.min( ...noDuplicates );
return highestNumber - lowestNumber - noDuplicates.length + 1;
}

console.log( nrOfMissedItems( source ) ); // 3
console.log( nrOfMissedItems( [1] ) ); // 0
console.log( nrOfMissedItems( [0,1,4] ) ); // 2
console.log( nrOfMissedItems( [5,3,1] ) ); // 2
console.log( nrOfMissedItems( [1,1,1,1,5] ) ); // 3
console.log( nrOfMissedItems( null ) ); // -Infinity
console.log( nrOfMissedItems( undefined ) ); // -Infinity
console.log( nrOfMissedItems() ); // -Infinity
console.log( nrOfMissedItems( ['a','b', 1] ) ); // NaN
console.log( nrOfMissedItems( ['a', null, 1] ) ); // NaN
console.log( nrOfMissedItems( [undefined, 1] ) ); // NaN

关于javascript - 从数组中获取缺失元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com