Description
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]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Solution
Two-pass XOR, time O(n), space O(1)
先取XOR,然后找到XOR中二进制为1的一位,然后根据它将nums分成两个group,然后分别取XOR即可。
class Solution {
public int[] singleNumber(int[] nums) {
int xor = 0;
for (int n : nums) {
xor ^= n;
}
// find one different digit
int mask = 1;
for (int i = 0; i < 32 && (xor & mask) == 0; ++i) {
mask <<= 1;
}
int[] res = new int[2];
// divide nums into two groups base on the different digit
for (int n : nums) {
if ((n & mask) == 0) {
res[0] ^= n;
} else {
res[1] ^= n;
}
}
return res;
}
}