-
Notifications
You must be signed in to change notification settings - Fork 0
/
N448_FindAllNumbersDisappearedInAnArray.java
60 lines (54 loc) · 1.52 KB
/
N448_FindAllNumbersDisappearedInAnArray.java
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
50
51
52
53
54
55
56
57
58
59
60
/**
* @Author: parallelline1996
* @Email: chenyu1996a@163.com
* @Date: 2019/12/22 20:54
*/
package page5;
import java.util.ArrayList;
import java.util.List;
/**
* 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 N448_FindAllNumbersDisappearedInAnArray {
public List<Integer> findDisappearedNumbers(int[] nums) {
boolean[] isContain = new boolean[nums.length];
for (int num : nums
) {
isContain[num - 1] = true;
}
List<Integer> response = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (!isContain[i]) {
response.add(i + 1);
}
}
return response;
}
public List<Integer> findDisappearedNumbers1(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int temp = Math.abs(nums[i]) - 1;
if (nums[temp] > 0) {
nums[temp] = -nums[temp];
}
}
List<Integer> response = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
response.add(i + 1);
}
}
return response;
}
}