一个整型数组里除了两个数字之外,其他的数字都出现了两次

来源:互联网 发布:公知和五毛是什么意思 编辑:程序博客网 时间:2024/05/18 03:09
题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

分析:这是一道很新颖的关于位运算的面试题。

首先我们考虑这个问题的一个简单版本:一个数组里除了一个数字之外,其他的数字都出现了两次。请写程序找出这个只出现一次的数字。这个题目的突破口在哪里?题目为什么要强调有一个数字出现一次,其他的出现两次?我们想到了异或运算的性质:任何一个数字异或它自己都等于0。也就是说,如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现一次的数字,因为那些出现两次的数字全部在异或中抵消掉了。

有了上面简单问题的解决方案之后,我们回到原始的问题。如果能够把原数组分为两个子数组。在每个子数组中,包含一个只出现一次的数字,而其他数字都出现两次。如果能够这样拆分原数组,按照前面的办法就是分别求出这两个只出现一次的数字了。


我们还是从头到尾依次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数字的异或结果。因为其他数字都出现了两次,在异或中全部抵消掉了。由于这两个数字肯定不一样,那么这个异或结果肯定不为0,也就是说在这个结果数字的二进制表示中至少就有一位为1。我们在结果数字中找到第一个为1的位的位置,记为第N位。现在我们以第N位是不是1为标准把原数组中的数字分成两个子数组,第一个子数组中每个数字的第N位都为1,而第二个子数组的每个数字的第N位都为0。

现在我们已经把原数组分成了两个子数组,每个子数组都包含一个只出现一次的数字,而其他数字都出现了两次。因此到此为止,所有的问题我们都已经解决。


代码如下:
[cpp] view plaincopyprint?
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. // Find the index of first bit which is 1 in num (assuming not 0)  
  5. unsigned int FindFirstBitIs1(int num)  
  6. {  
  7.  int indexBit = 0;  
  8.  while (((num & 1) == 0) && (indexBit < 32))  
  9.  {  
  10.    num = num >> 1;  
  11.    ++ indexBit;  
  12.  }  
  13.  return indexBit;  
  14. }  
  15.   
  16. // Is the indexBit bit of num 1?  
  17. bool IsBit1(int num, unsigned int indexBit)  
  18. {  
  19.  num = num >> indexBit;  
  20.  trturn (num & 1);   
  21. }  
  22.   
  23. // Find two numbers which only appear once in an array  
  24. // Input: data - an array contains two number appearing exactly once,  
  25. void FindNumsAppearOnce(int data[], int length, int &num1, int &num2)  
  26. {  
  27.       if (length < 2)    return;  
  28.       // get num1 ^ num2  
  29.       int resultExclusiveOR = 0;  
  30.       for (int i = 0; i < length; ++ i)  
  31.             resultExclusiveOR ^= data[i];  
  32.    
  33.       // get index of the first bit, which is 1 in resultExclusiveOR  
  34.       unsigned int indexOf1 = FindFirstBitIs1(resultExclusiveOR);   
  35.       num1 = num2 = 0;  
  36.       for (int j = 0; j < length; ++ j)  
  37.       {  
  38.             // divide the numbers in data into two groups,  
  39.             // the indexOf1 bit of numbers in the first group is 1,  
  40.             // while in the second group is 0  
  41.             if(IsBit1(data[j], indexOf1))  
  42.                   num1 ^= data[j];  
  43.             else  
  44.                   num2 ^= data[j];  
  45.       }  
  46. }  
  47.   
  48. int main()  
  49. {  
  50.   int a[8] = {2,3,6,8,3,2,7,7};  
  51.   int x,y;  
  52.   FindNumsAppearOnce(a,8,x,y);  
  53.   cout<<x<<"\t"<<y<<endl;  
  54.   return 0;  
  55. }   
0 0