forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_442.java
41 lines (36 loc) · 1.05 KB
/
_442.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class _442 {
public static class Solution1 {
//O(n) space
//O(n) time
public List<Integer> findDuplicates(int[] nums) {
Set<Integer> set = new HashSet();
List<Integer> result = new ArrayList();
for (int i : nums) {
if (!set.add(i)) {
result.add(i);
}
}
return result;
}
}
public static class Solution2 {
//O(1) space
//O(n) time
public List<Integer> findDuplicates(int[] nums) {
List<Integer> result = new ArrayList();
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
result.add(Math.abs(index + 1));
}
nums[index] = -nums[index];
}
return result;
}
}
}