简体   繁体   English

从1..N items数组中找到缺少的项目

[英]Find missing item from 1..N items array

I was asked to find the missing number from 1..N array. 我被要求从1..N数组中找到丢失的数字。

For instance, for array: let numArr = [2,4,6,8,3,5,1,9,10]; 例如,对于array: let numArr = [2,4,6,8,3,5,1,9,10]; the missing number is 7 缺少的数字是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;
  }
}

You can use MAP and FILTER to find out the missing number in seperate array 您可以使用MAPFILTER找出单独数组中缺少的数字

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);

You can use the simple logic of sum of consecutive n numbers is n*(n+1)/2 . 您可以使用连续n个数的和的简单逻辑是n*(n+1)/2 Subtracting the sum of array numbers from above will give the missing number 从上面减去数组的总和将得到缺失的数字

 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); 

It would be easier to use .find : 它会更容易使用.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])); 

(note that this also works for finding missing values from arrays that don't start at 1) (请注意,这也适用于从不从1开始的数组中查找缺失值)

You can use XOR features. 您可以使用XOR功能。

  • XOR all the array elements, let the result of XOR be arr_xor . XOR所有数组元素,让XOR的结果为arr_xor
  • XOR all numbers from 1 to n, let XOR be interval_xor . XOR从1到n的所有数字,让XOR为interval_xor
  • XOR of arr_xor and interval_xor gives the missing number. arr_xorinterval_xor XOR给出了缺失的数字。

 let numArr=[2,4,6,8,3,5,1,9,10]; function getMissingNo(arr){ arr = arr.sort() n = arr.length arr_xor = arr[0] interval_xor = 1 for(i = 0; i < n; i++) arr_xor ^= arr[i] for( i = 0; i<n + 2; i++) interval_xor ^= i return arr_xor ^ interval_xor } console.log(getMissingNo(numArr)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM