(1、原题如下:
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?
2、解题如下:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int a=0,b=0;
for(int i:nums) a^=i;//利用xor找出两个数,形式为类似3^5
for(int i:nums) if(i&a&-a) b^=i;//判断条件非常关键,继续遍历,然后由于xor的特性,利用a&-a的技巧,先写出一个1,然后尾位为1(这里尾位定义为最后一个为1的位)的还是会被两次异或刷掉,因为留下的两个数必然有一个是有尾位而另一个没有(想想为什么),b被找出来后,另一个也就被找出来了
return {a^b,b};
}
};