剑指offer(20)-数组中只出现一次的数字

来源:互联网 发布:php-> 编辑:程序博客网 时间:2024/06/15 03:14

题目:

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

思路: 经典题目,利用异或运算解决效率最高。异或运算规则: 0 ^ num = num, 1 ^ num = ~num, num ^ num = 0. 因此一次异或运算结束后肯定有某位不为0,找出所在位,根据这位是否为1把数组元素分为两组,再使用异或运算就可以求出这个找出这个数字。

代码如下:

public class Solution {    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {        if (array.length < 2)            return;        int ResultExclusionOR = 0;        for (int i = 0;i < array.length;++i)            ResultExclusionOR ^= array[i];        int IndexOf1 = FindFirstBitIs1(ResultExclusionOR);        num1[0] = num2[0] = 0;        for (int j = 0;j < array.length;++j) {            if (IsBit1(array[j], IndexOf1))            {                num1[0] ^= array[j];            }            else                num2[0] ^= array[j];            }    }    public int FindFirstBitIs1(int num)    {        int IndexBit = 0;        while ((num & 1) == 0)        {               num = num >> 1;            ++ IndexBit;        }        return IndexBit;    }    public boolean IsBit1(int num,int IndexBit)    {        num = num >> IndexBit;        return ((num & 1) == 1);    }}
1 0