Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
public class Solution {
public int[] singleNumber(int[] nums) {
int a = 0;
int b = 0;
for (int i : nums) {
a ^= i;
}
int rightOne = a & (~a + 1);
for (int i : nums) {
if ((rightOne & i) != 0) {
b ^= i;
}
}
return new int[]{b, a^b};
}
}