Voyz's Studio.

LeetCode算法笔记--找到所有数组中消失的数字

字数统计: 251阅读时长: 1 min
2021/02/12 Share

LeetCode算法笔记-Day67

448. Find All Numbers Disappeared in an Array

1
2
3
4
5
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.
1
2
3
4
5
6
7
8
Example:

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

Output:
[5,6]

方法一:原地修改

  • 遍历输入数组的每个元素一次。
  • 我们将把 |nums[i]|-1 索引位置的元素标记为负数。即 nums[|nums[i] |- 1] \times -1nums[∣nums[i]∣−1]×−1 。
  • 然后遍历数组,若当前数组元素 nums[i] 为负数,说明我们在数组中存在数字 i+1。

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDisappearedNumbers = function(nums) {
let res = [];

//标记索引元素
for(let i=0;i<nums.length;i++){
if(nums[Math.abs(nums[i])-1]>0){
nums[Math.abs(nums[i])-1] *= -1;
}
}

// 寻找未标记下标
for(let j=0;j<nums.length;j++){
if(nums[j]>0) res.push(j+1)
}

return res;
};
CATALOG
  1. 1. LeetCode算法笔记-Day67
    1. 1.1. 448. Find All Numbers Disappeared in an Array
    2. 1.2. 方法一:原地修改
      1. 1.2.1. Answer: