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

题目:

  数组中只出现一次的数字

链接:

  https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&tPage=2&rp=4&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题目描述:

  一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

思路:

  出现两次的数字可以异或为零,具体思路见剑指offer

代码:

 1 class Solution {
 2 public:
 3     void FindNumsAppearOnce(vector<int> data, int* num1, int* num2){
 4         int len = data.size();
 5         if(len<2)
 6               return ;
 7         int temp = 0;
 8         for(int x:data){
 9             temp ^= x;
10         }
11         unsigned int val = First1(temp);
12         * num1 = *num2 = 0;
13         for(int x :data){
14             if(is1(x,val)){
15                 *num1 ^= x;
16             }
17             else{
18                 *num2 ^= x;
19             }
20         }
21     }
22     unsigned int First1(int a){
23         int x =0;
24         while((a&1)==0 && (x <8*sizeof(int))){
25             a=a>>1;
26             ++x;
27         }
28         return x;
29     }
30     bool is1(int x, unsigned int val){
31         x = x >>val;
32         if((x&1)==1)
33               return true;
34         return false;
35     }
36 };
原文地址:https://www.cnblogs.com/wangshujing/p/6945496.html