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

来源:互联网 发布:tts软件怎么用 编辑:程序博客网 时间:2024/04/30 08:16

首先来一道简单的题目:一个数组中,除了一个数字,其他数字都出现了两次,我们如何找出那个不同的数字,

很简单,将所有的数字都异或,那么最终结果就是要找的数字,因为相同的数字异或结果就是0

那么现在来思考这个题目:

《编程之美》一书提供了一种方法,即将所有的数字进行一个异或,得到一个数字,然后以该数字的某非0为作为过滤位,将数组分为两个部分,此时出现一次的数字会分到不同的部分,现在的问题就已经转换为出现一次的情况:

算法如下:

[java] view plaincopyprint?
  1. public int[]findTwoDiff(int[]a)  
  2.     {  
  3.         int []result=new int[2];  
  4.         int temp=0;  
  5.         int flag=1;  
  6.         for(int t:a)  
  7.         {  
  8.             temp^=t;  
  9.         }  
  10.           
  11.         while((temp&flag)==0)  
  12.         {  
  13.             flag<<=1;  
  14.         }  
  15.         for(int t:a)  
  16.         {  
  17.             if((t&flag)==1)  
  18.             {  
  19.                 result[0]^=t;  
  20.             }else  
  21.             {  
  22.                 result[1]^=t;  
  23.             }  
  24.         }  
  25.           
  26.         return result;  
  27.           
  28.     }  
  29. 转载自:http://blog.csdn.net/yuanzeyao/article/details/8035002