leedcode 數組:448. Find All Numbers Disappeared in an Array

題目描述

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

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

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

Example:segmentfault

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

Output:
[5,6]app

思路

先把數組進行升序排序,再進行數組去重,最後循環比較取得結果。post

升序排序可使用:this

array.sort (function (a, b) {
    return a - b;  // 若要降序排列能夠則是 b - a
});

數組去重,我使用的ES6中的Set方法去重,能夠參照:
一行代碼實現數組去重(ES6)
JavaScript 數組去重
JS數組去重方法最優解spa

源碼

/**
 * @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;
};
相關文章
相關標籤/搜索