Skip to content

Commit 598e1bc

Browse files
authored
Add files via upload
1 parent 14db620 commit 598e1bc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

FindAllDuplicates.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
//https://leetcode.com/problems/find-all-duplicates-in-an-array/
5+
public class FindAllDuplicates {
6+
7+
//Approach:
8+
// As given that numbers in array are postive and in the range of array.length
9+
//while iterating make the value at index as negative before making it negative check if it is already negative means
10+
// it is already visited hence the index would be duplicate value as it is already visited
11+
12+
13+
14+
public List<Integer> findDuplicates(int[] nums) {
15+
List<Integer> res = new ArrayList<>();
16+
for(int i=0;i<nums.length;i++) {
17+
if(nums[Math.abs(nums[i])-1]<0) {
18+
res.add(Math.abs(nums[i]));
19+
} else {
20+
nums[Math.abs(nums[i])-1]*=-1;
21+
}
22+
}
23+
return res;
24+
}
25+
}
26+
27+
28+
//Similar would be the approach for finding all disappeared numbers in the array, while iterating make all values at the
29+
// index as negatives and iterate through the array again to find all postive values and add the indexes into the result

0 commit comments

Comments
 (0)