class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
使用位运算找到两个只出现一次的数字
因为异或运算中出现偶数次的数字会互相抵消为零,所以对整个数组使用异或运算得到的最后结果和只对这两个不同的数字使用异或得到的结果是一样的
结果中为1的位置就是两个数字位运算中不同位的位置
2 : 10
4 : 100
2 ^ 4 = 110 = 5
从得到的结果找到他们不同位的位置,遍历整个数组,根据这个不同位把数组一分为二,分别异或,最后相同的数就会抵消掉。
*/
bool find(int x, int index){
x = x >> index;
return x & 1 != 0;
}
vector FindNumsAppearOnce(vector& array) {
vector res;
int result = 0;
for(int i = 0; i
result ^= array[i];//得到整个数组异或后的结果
}
int index = 0;
while((result & 1) == 0 ){
result = result >> 1;
index ++;//得到两个不同数他们第一个的不同位,我们只需要知道一个就好
}
int a = 0, b = 0;
for(int i = 0; i
if(find(array[i], index))//通过判断在不同位上的值,来将数组分割成两个,分别异或
a ^= array[i];//相同的数会自己抵消掉,只剩下出现一次的数
else
b ^= array[i];
}
if(a
res.push_back(a);
res.push_back(b);
}
else{
res.push_back(b);
res.push_back(a);
}
return res;
}
};