题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次,请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
https://cuijiahua.com/blog/2018/01/basis_40.html
bool isBitOne(int num,int index) {
return (num>>index)%2 == 1;
}
bool diffTwo(int a[],int len, int *one,int *two) {
if (NULL == a || len <=0) {
return false;
}
int ret = a[0];
for (int i = 1; i<len; i++) {
ret = ret ^ a[i];
}
int k = 0;
while (ret%2 != 1) {
ret = ret / 2;
k++;
}
for (int j = 0; j<len; j++) {
if (isBitOne(a[j],k)) {
*one = *one ^ a[j];
}
else {
*two = *two ^ a[j];
}
}
return true;
}
int diffData[] = {2,4,3,6,3,2,5,5};
int diffO = 0;
int diffT = 0;
diffTwo(diffData, 8, &diffO, &diffT);