题目
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.
Example:
Input: [1,2,1,3,2,5]
Output: [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?
分析
1、与0做异或仍为原来的数;与1做异或相当于取反
2、相同的数做异或得到0
1o 首先我们要将只出现一次的数从数组中分离出来,那么和single number那道题目一样,将数组中所有数做异或,出现两次的都异或为0不对数值再做影响,所以最后得到的是a XOR b。
2o 那么如何从a XOR b中将a和b分离出来呢?
只这一个数显然不行,所以我们又回到数组,联想single number只一个数出现一次,那么我们这道题是不是可以将原数组分成两部分,一部分包含a,另一部分包含b,然后用single number的方法就可以找到a和b了呢
3o 如何分类原数组将其分成两部分?
既然要找把a和b分在两队,那当然是找a和b的不同了。观察aXORb,该位为0那么说明a和b的该位相同,同为0或同为1;该位为1说明a和b该位上恰一个为0一个为1(究竟是a的这一位为0还是b的这一位为0不重要,因为题目不要求输出顺序) ,以此分类。
综上所述,选择一位aXORb中为1的一位,将原数组中该位为0的分为一组,做异或,结果为a,将原数组中该位为1的分为一组,做异或,结果为b
代码
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int x=0;
for(auto i:nums){
x=x^i;
}
int index=0;
int n=sizeof(int)*8;
for(;index<n;++index){
if(((x>>index)&1)==1){
break;
}
}
int a=0;
int b=0;
for(auto i: nums){
if(((i>>index)&1)==0){
a=a^i;
}
else{
b=b^i;
}
}
vector<int> r;
r.push_back(a);
r.push_back(b);
return r;
}
};