Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 84cc7a4

Browse files
author
Ram swaroop
committed
two repeating elements : 90% done
1 parent 235bb4a commit 84cc7a4

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

src/me/ramswaroop/arrays/TwoRepeatingElements.java

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package me.ramswaroop.arrays;
22

3+
import java.util.Arrays;
4+
35
/**
46
* Created by IntelliJ IDEA.
57
*
@@ -10,10 +12,37 @@
1012
public class TwoRepeatingElements {
1113

1214
public static int[] getTwoRepeatingElements(int[] a) {
13-
15+
int xor = a[0];
16+
int rightMostSetBit;
17+
int x = 0, y = 0;
18+
for (int i = 1; i < a.length; i++) {
19+
xor ^= a[i];
20+
}
21+
for (int i = 1; i <= a.length - 2; i++) {
22+
xor ^= i;
23+
}
24+
rightMostSetBit = xor & ~(xor - 1);
25+
26+
for (int i = 0; i < a.length; i++) {
27+
if ((a[i] & rightMostSetBit) == 1) {
28+
x ^= a[i];
29+
} else {
30+
y ^= a[i];
31+
}
32+
}
33+
34+
for (int i = 1; i <= a.length - 2; i++) {
35+
if ((i & rightMostSetBit) == 1) {
36+
x ^= i;
37+
} else {
38+
y ^= i;
39+
}
40+
}
41+
42+
return new int[]{x, y};
1443
}
1544

1645
public static void main(String a[]) {
17-
46+
System.out.println(Arrays.toString(getTwoRepeatingElements(new int[]{4, 2, 4, 5, 2, 3, 1})));
1847
}
1948
}

0 commit comments

Comments
 (0)