-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathFindAllMissing.java
More file actions
31 lines (28 loc) · 836 Bytes
/
Copy pathFindAllMissing.java
File metadata and controls
31 lines (28 loc) · 836 Bytes
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
28
29
30
31
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/find-all-duplicates-in-an-array/
public class FindAllDuplicates {
public List<Integer> findDuplicates(int[] arr) {
int i = 0;
while (i < arr.length) {
int correct = arr[i] - 1;
if (arr[i] != arr[correct]) {
swap(arr, i , correct);
} else {
i++;
}
}
List<Integer> ans = new ArrayList<>();
for (int index = 0; index < arr.length; index++) {
if (arr[index] != index+1) {
ans.add(arr[index]);
}
}
return ans;
}
static void swap(int[] arr, int first, int second) {
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}