AcWing 73. 数组中只出现一次的两个数字
原题链接
中等
作者:
一凡
,
2019-04-11 10:59:57
,
所有人可见
,
阅读 1108
class Solution {
public:
vector<int> findNumsAppearOnce(vector<int>& nums) {
int length = nums.size();
vector<int> res;
if(length<2) return res;
// 对原始数组每个元素求异或
int OR = 0;
for(int i=0;i<length;i++){
OR ^= nums[i];
}
unsigned int indexOf1 = findFirstBit1(OR);
int num1=0,num2=0;
for(int i=0;i<length;i++){
if(isBit1(nums[i],indexOf1)){
num1 ^= nums[i];
}
else{
num2 ^= nums[i];
}
}
res.push_back(num1);
res.push_back(num2);
return res;
}
int findFirstBit1(int num){
unsigned int index = 0;
while((num&1)==0 && (index<8*sizeof(unsigned int))){
num = num>>1;
index++;
}
return index;
}
bool isBit1(int num,int index){
num = num>>index;
return (num&1);
}
};