我正在尝试编写一个函数来查找数组中所有缺少的元素.该系列从1 ... n开始.输入是未排序的数组,输出是缺少的数字.
以下是我到目前为止:
function findMissingElements(arr) { arr = arr.sort(); var missing = []; if (arr[0] !== 1) { missing.unshift(1); } // Find the missing array items for (var i = 0; i < arr.length; i++) { if ((arr[i + 1] - arr[i]) > 1) { missing.push(arr[i + 1] - 1); } } return missing; } var numbers = [1, 3, 4, 5, 7, 8]; // Missing 2,6 var numbers2 = [5, 2, 3]; //missing 1, 4 var numbers3 = [1, 3, 4, 5, 7]; // Missing 2,6 console.log(findMissingElements(numbers)); // returns 2,6 correct console.log(findMissingElements(numbers2)); // returns 1,4 console.log(findMissingElements(numbers3)); // returns 2, 6
我用"if"块"手动"检查了第一个元素,有没有办法处理for循环中第一个元素的情况?
您可以通过跟踪下一个应显示的数字并将其添加到缺失数字列表中,同时小于下一个数字来生成该数字.
function findMissingElements(arr) { // Make sure the numbers are in order arr = arr.slice(0).sort(function(a, b) { return a - b; }); let next = 1; // The next number in the sequence let missing = []; for (let i = 0; i < arr.length; i++) { // While the expected element is less than // the current element while (next < arr[i]) { // Add it to the missing list and // increment to the next expected number missing.push(next); next++; } next++; } return missing; }