剑指offer 数组中只出现一次的数字

时间:2021-02-17 14:32:38

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。  注意:data[j] & lastBit 最后出来的结果是00000000,不能直接写成data[j] & lastBit == 0,这样是错误的,0是整数,前面是二进制,后面是十进制,不能直接进行比较大小,必须进行进制转换。 思路:如果两个数一样,那么他们异或的大小就是零,首先将数组进行全部进行异或,得到xor, xor & (xor - 1)可以去掉最后一位等于1的那一位,然后使用xor - xor & (xor - 1)就可以得到最后一位等于1的那个数。将数组的数和lastbits相&,可以将数组分为两部分,将两个数就分开了,然后分别进行异或运算,就可以得到结果。 
class Solution {
public:
void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
if(data.size() == 0){
return;
}
int XOR = 0;
for(int i = 0;i < data.size();++i){
XOR
^= data[i];
}
int lastBit = XOR -(XOR & (XOR - 1));
int left = 0,right = 0;
for(int j = 0;j < data.size();++j){
if(data[j] & lastBit){
right
^= data[j];
}
else{
left
^= data[j];
}
}
*num1 = left;
*num2 = right;
return;
}
};