442. Find All Duplicates in an Array

Flip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> list = new ArrayList<>();

for (int i = 0; i < nums.length; i++) {
int abs = Math.abs(nums[i]);
if (nums[abs - 1] < 0) {
// 已经被翻转过,收集该数字
list.add(abs);
} else {
nums[abs - 1] = -nums[abs - 1];
}
}

return list;
}
}

Hash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> numList = new ArrayList<>();

for (int i = 0; i < nums.length; i++) {
int targetIndex = nums[i] - 1;
while (nums[i] != nums[targetIndex]) {
swap(nums, i, targetIndex);
targetIndex = nums[i] - 1;
}
}

for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
numList.add(nums[i]);
}
}

return numList;
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}

References

442. Find All Duplicates in an Array