-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathFindAllNumbersDisappearedInAnArray448.java
More file actions
49 lines (46 loc) · 1.26 KB
/
FindAllNumbersDisappearedInAnArray448.java
File metadata and controls
49 lines (46 loc) · 1.26 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 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:
*
* Input:
* [4,3,2,7,8,2,3,1]
*
* Output:
* [5,6]
*/
public class FindAllNumbersDisappearedInAnArray448 {
public List<Integer> findDisappearedNumbers(int[] nums) {
if (nums == null || nums.length <= 1) return new ArrayList<>();
int len = nums.length;
int i = 0;
while (i < len) {
int curr = nums[i];
while (curr != i + 1) {
int next = nums[curr-1];
if (curr == next) break;
swap(nums, i, curr-1);
curr = nums[i];
}
i++;
}
List<Integer> res = new ArrayList<>();
for (int j=0; j<len; j++) {
if (nums[j] != j+1) {
res.add(j+1);
}
}
return res;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}