forked from havanagrawal/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_448.java
86 lines (71 loc) · 2.14 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 448. Find All Numbers Disappeared in an Array
*
* 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 _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;
}
}
}