-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-6 Find All Duplicates in an Array
85 lines (68 loc) · 1.88 KB
/
Day-6 Find All Duplicates in an Array
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
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == nums[i]) {
ans.add(nums[i]);
break;
}
}
}
return ans;
}
}
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
ans.add(nums[i]);
i++; // skip over next element
}
}
return ans;
}
}
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) {
ans.add(num);
} else {
seen.add(num);
}
}
return ans;
}
}
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int num : nums) {
nums[Math.abs(num) - 1] *= -1;
}
for (int num : nums) {
if (nums[Math.abs(num) - 1] > 0) {
ans.add(Math.abs(num));
nums[Math.abs(num) - 1] *= -1;
}
}
return ans;
}
}
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
for (int num : nums) {
if (nums[Math.abs(num) - 1] < 0) { // seen before
ans.add(Math.abs(num));
}
nums[Math.abs(num) - 1] *= -1;
}
return ans;
}
}