我被要求从1..N
数组找到丢失的号码。
例如,对于数组:let numArr = [2,4,6,8,3,5,1,9,10];
,缺少的数字为7
let numArr=[2,4,6,8,3,5,1,9,10];
numArr.sort(function(a,b){ //sort numArr
return a-b;
});
let newNumArr=[];
for(let i=1;i<=10;i++){
newNumArr.push(i);
}
for(let i=0;i<newNumArr.length;i++){ //compare with new arr
if(newNumArr[i] !== numArr[i]){
console.log('The missing num is:'+newNumArr[i]); //The missing num is:7
break;
}
}
答案 0 :(得分:6)
您可以使用MAP
和FILTER
找出单独数组中缺少的数字
const numArr = [2, 4, 6, 8, 3, 5, 1, 9, 10];
const missingNumberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(number => {
if (!numArr.includes(number)) {
return number;
}
}).filter(y => y !== undefined);
答案 1 :(得分:4)
您可以使用连续n
个数之和的简单逻辑n*(n+1)/2
。从上面减去数组的总和将得到缺失的数字
let numArr=[2,4,6,8,3,5,1,9,10];
var sum = numArr.reduce((a,c) => a+c, 0);
// As the array contains n-1 numbers, here n will be numArr.length + 1
console.log(((numArr.length + 1) * (numArr.length + 2))/2 - sum);
&#13;
答案 2 :(得分:2)
使用.find
:
function findMissing(input) {
input.sort((a, b) => a - b);
const first = input[0];
return input.find((num, i) => first + i !== num) - 1;
}
console.log(findMissing([2, 4, 6, 8, 3, 5, 1, 9, 10]));
console.log(findMissing([3, 4, 5, 6, 8, 9, 2]));
(请注意,这也适用于从1开始的数组中查找缺失值)