Created
May 9, 2021 09:56
-
-
Save ankit167/089e6907e2ad6aab5151832483e2e53e to your computer and use it in GitHub Desktop.
Find two elements in the array that are not repeated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Input: 2 1 7 4 5 4 7 1 | |
// Output: 2 5 | |
public void findTwoElements(int[] a) { | |
int xor = 0, x = 0, y = 0, rsb; | |
for (int i = 0; i < a.length; i++) { | |
xor = xor ^ a[i] | |
} | |
rsb = xor & ~(xor-1); | |
for (int i = 0; i < a.length; i++) { | |
if (a[i] & rsb == 0) { | |
x = x ^ a[i]; | |
} else { | |
y = y ^ a[i]; | |
} | |
} | |
System.out.println(x); | |
System.out.println(y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment