-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_duplicates_in_an_array.java
45 lines (44 loc) · 1.21 KB
/
find_duplicates_in_an_array.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
//most optimized approach O(n) time space O(1)
class Solution {
public List<Integer> findDuplicates(int[] nums) {
// HashSet<Integer>hs = new HashSet<>();
List<Integer> ans = new ArrayList<Integer>();
for(int i = 0 ; i < nums.length ; i++){
int idx = Math.abs(nums[i])-1;
if(nums[idx] >= 0){
nums[idx] = - nums[idx];
}else{
ans.add(Math.abs(nums[i]));
}
}
return ans;
}
}
//approach 2 using hashset
class Solution {
public List<Integer> findDuplicates(int[] nums) {
HashSet<Integer>hs = new HashSet<>();
List<Integer> ans = new ArrayList<Integer>();
for(int i:nums){
if(hs.contains(i)==false){
hs.add(i);
}else{
ans.add(i);
}
}
return ans;
}
}
//approach 3 using sorting
class Solution {
public List<Integer> findDuplicates(int[] nums) {
Arrays.sort(nums);
List<Integer> ans = new ArrayList<Integer>();
for(int i =0;i<nums.length-1 ;i++){
if(nums[i] ==nums[i+1] ){
ans.add(nums[i]);
}
}
return ans;
}
}