forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_448.java
70 lines (59 loc) · 1.7 KB
/
_448.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
61
62
63
64
65
66
67
68
69
70
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class _448 {
public static class Solution1 {
/**
* O(n) space
* O(n) time
*/
public List<Integer> findDisappearedNumbers(int[] nums) {
int max = Integer.MIN_VALUE;
for (int i : nums) {
max = Math.max(max, i);
}
max = Math.max(max, nums.length);
Map<Integer, Integer> map = new HashMap();
for (int i = 1; i <= max; i++) {
map.put(i, 0);
}
for (int i : nums) {
if (map.get(i) == 0) {
map.put(i, 1);
} else {
map.put(i, map.get(i) + 1);
}
}
List<Integer> result = new ArrayList();
for (int i : map.keySet()) {
if (map.get(i) == 0) {
result.add(i);
}
}
return result;
}
}
public static class Solution2 {
/**
* O(1) space
* O(n) time
*/
public List<Integer> findDisappearedNumbers(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int val = Math.abs(nums[i]) - 1;
if (nums[val] > 0) {
nums[val] = -nums[val];
}
}
List<Integer> result = new ArrayList();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
result.add(i + 1);
}
}
return result;
}
}
}