题目描述

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

思路

先把数组进行升序排序,再进行数组去重,最后循环比较取得结果。

升序排序可以使用:

array.sort (function (a, b) {
    return a - b;  // 若要降序排列可以则是 b - a
});

数组去重,我使用的ES6中的Set方法去重,可以参照:
一行代码实现数组去重(ES6)
JavaScript 数组去重
JS数组去重方法最优解

源码

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
  // 排序
  let numList = nums.sort(function (a, b) {
    return a - b;
  });
  let numLength = nums.length;
  // 去重
  numList = Array.from(new Set(numList));
  let i = 0,
      a = [];

  for (let n = 1; n < numLength + 1; n++) {
    if (n > numList[numList.length - 1]) {
      a.push(n);
    } else {
      if (n == numList[i]) {
        i++;
      } else if (n < numList[i]) {
        a.push(n);
      }
    }
  }

  return a;
};

puhongru
581 声望58 粉丝

立志成为一名合格的前端开发工程师