11
11
*/
12
12
public class TwoRepeatingElements {
13
13
14
+ /**
15
+ * Finds the 2 repeating elements in an array {@param a} of 1 to n elements and n+2 length. This is
16
+ * similar to {@link me.ramswaroop.bits.TwoNonRepeatingElements}.
17
+ * <p/>
18
+ * EXPLANATION:
19
+ * Let the repeating numbers be X and Y, if we xor all the elements in the array and all integers from 1 to n,
20
+ * then the result is X xor Y.
21
+ * The 1’s in binary representation of X xor Y is corresponding to the different bits between X and Y.
22
+ * Suppose that the kth bit of X xor Y is 1, we can xor all the elements in the array and all integers
23
+ * from 1 to n, whose kth bits are 1. The result will be one of X and Y.
24
+ *
25
+ * @param a
26
+ * @return
27
+ */
14
28
public static int [] getTwoRepeatingElements (int [] a ) {
15
29
int xor = a [0 ];
16
30
int rightMostSetBit ;
17
31
int x = 0 , y = 0 ;
18
-
32
+
19
33
for (int i = 1 ; i < a .length ; i ++) {
20
34
xor ^= a [i ];
21
35
}
36
+
22
37
for (int i = 1 ; i <= a .length - 2 ; i ++) {
23
38
xor ^= i ;
24
39
}
40
+
41
+ // now xor is X xor Y, therefore find any of its set bit
25
42
rightMostSetBit = xor & ~(xor - 1 );
26
43
27
44
for (int i = 0 ; i < a .length ; i ++) {
45
+ // one number will have a set bit at that position and other wouldn't
28
46
if ((a [i ] & rightMostSetBit ) == 0 ) {
29
47
x ^= a [i ];
30
48
} else {
@@ -33,6 +51,7 @@ public static int[] getTwoRepeatingElements(int[] a) {
33
51
}
34
52
35
53
for (int i = 1 ; i <= a .length - 2 ; i ++) {
54
+ // one number will have a set bit at that position and other wouldn't
36
55
if ((i & rightMostSetBit ) == 0 ) {
37
56
x ^= i ;
38
57
} else {
@@ -45,5 +64,7 @@ public static int[] getTwoRepeatingElements(int[] a) {
45
64
46
65
public static void main (String a []) {
47
66
System .out .println (Arrays .toString (getTwoRepeatingElements (new int []{4 , 2 , 4 , 5 , 2 , 3 , 1 })));
67
+ System .out .println (Arrays .toString (getTwoRepeatingElements (new int []{2 , 4 , 5 , 2 , 3 , 1 , 6 , 7 , 7 })));
68
+ System .out .println (Arrays .toString (getTwoRepeatingElements (new int []{1 , 2 , 1 , 2 })));
48
69
}
49
70
}
0 commit comments