File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments