一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路:1.任何数亦或自己等于0, a^a == 0;
2.遍历数组,亦或一遍,得到2个出现一次数字亦或的值。
3. 找到这2个数字二进制数不同的那一位。将数组分成2组,这样每个子数组就变成了:有n个数出现2次,1个数出现1次。
4.利用亦或性质,求出这2个数
class Solution { public: void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) { int tmp =0; for (auto it=data.begin();it<data.end();it++){ tmp ^=(*it); } int index = 0; while((tmp&1)==0){ index++; tmp=tmp>>1; } for (auto it=data.begin();it<data.end();it++){ if((*it>>index)&1==1){ *num1 ^=(*it); }else{ *num2 ^=(*it); } } } };