原题:
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?
解决方法:
- 求异或的结果,即a^b.
- 求a和b的最后一个不同位。
- 根据这个不同位,把数组分成两部分,a和b各在一部分。
代码:
vector<int> singleNumber(vector<int>& nums) {
int xOr = 0;
for(int i = 0; i < nums.size();i++)
xOr ^= nums[i];
int lastBit = (xOr & (xOr -1)) ^ xOr;
int num1 = 0, num2 = 0;
for(int i = 0; i < nums.size(); i++){
if (lastBit & nums[i])
num1 ^= nums[i];
else
num2 ^= nums[i];
}
return vector<int>{num1, num2};
}