@@ -62,9 +62,37 @@ public static int[] getTwoRepeatingElements(int[] a) {
62
62
return new int []{x , y };
63
63
}
64
64
65
+ /**
66
+ * The algorithm is simple. We use index of the array to track repeating elements.
67
+ * Once we encounter a element lets say 2 then we make the 2nd index -ve just to mark
68
+ * that we have encountered 2. When we encounter 2 again and see that 2nd index
69
+ * is already -ve we conclude that 2 is repeated.
70
+ *
71
+ * Similar to {@link me.ramswaroop.arrays.DuplicatesInArray#findDuplicatesInArray(int[])}.
72
+ *
73
+ * @param a
74
+ * @return
75
+ */
76
+ public static int [] findTwoRepeatingElements (int [] a ) {
77
+ int [] repeatingElements = new int [2 ];
78
+
79
+ for (int i = 0 , j = 0 ; i < a .length ; i ++) {
80
+ if (a [Math .abs (a [i ])] >= 0 ) {
81
+ a [Math .abs (a [i ])] = -a [Math .abs (a [i ])];
82
+ } else {
83
+ repeatingElements [j ++] = Math .abs (a [i ]);
84
+ }
85
+ }
86
+ return repeatingElements ;
87
+ }
88
+
65
89
public static void main (String a []) {
66
90
System .out .println (Arrays .toString (getTwoRepeatingElements (new int []{4 , 2 , 4 , 5 , 2 , 3 , 1 })));
67
91
System .out .println (Arrays .toString (getTwoRepeatingElements (new int []{2 , 4 , 5 , 2 , 3 , 1 , 6 , 7 , 7 })));
68
92
System .out .println (Arrays .toString (getTwoRepeatingElements (new int []{1 , 2 , 1 , 2 })));
93
+ System .out .println ("========" );
94
+ System .out .println (Arrays .toString (findTwoRepeatingElements (new int []{4 , 2 , 4 , 5 , 2 , 3 , 1 })));
95
+ System .out .println (Arrays .toString (findTwoRepeatingElements (new int []{2 , 4 , 5 , 2 , 3 , 1 , 6 , 7 , 7 })));
96
+ System .out .println (Arrays .toString (findTwoRepeatingElements (new int []{1 , 2 , 1 , 2 })));
69
97
}
70
98
}
0 commit comments