Google
448 Find All Numbers Disappeared in an Array

1. Question

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:
1
Input: [4,3,2,7,8,2,3,1]
2
3
4
Output: [5,6]
Copied!

2. Implementation

(1) HashTable
1
class Solution {
2
public List<Integer> findDisappearedNumbers(int[] nums) {
3
List<Integer> res = new ArrayList<>();
4
5
if (nums == null || nums.length == 0) {
6
return res;
7
}
8
9
int n = nums.length;
10
int[] map = new int[n + 1];
11
12
for (int num : nums) {
13
++map[num];
14
}
15
16
for (int i = 1; i <= n; i++) {
17
if (map[i] == 0) {
18
res.add(i);
19
}
20
}
21
return res;
22
}
23
}
Copied!
(2) Follow Up 空间优化
1
class Solution {
2
public List<Integer> findDisappearedNumbers(int[] nums) {
3
List<Integer> res = new ArrayList<>();
4
5
if (nums == null || nums.length == 0) {
6
return res;
7
}
8
9
for (int i = 0; i < nums.length; i++) {
10
int index = Math.abs(nums[i]) - 1;
11
if (nums[index] > 0) {
12
nums[index] *= -1;
13
}
14
}
15
16
for (int i = 1; i <= nums.length; i++) {
17
if (nums[i - 1] > 0) {
18
res.add(i);
19
}
20
}
21
return res;
22
}
23
}
Copied!

3. Time & Space Complexity

HashTable: 时间复杂度O(n), 空间复杂度O(n)
Follow Up 空间优化:时间复杂度O(n), 空间复杂度O(n)