剑指offer:数组中只出现一次的数字

题目

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

解题思路

对于一个简单的问题:找出数组中只出现一次的数字,我们使用异或操作对出现两次的数字进行抵消,最后的结果就是只出现一次的数组。
对于这个问题,我们可以把数字分成两个数组,各自包含一个只出现一次的数字。但是这个怎么划分?
我们先对数组进行全部的异或操作,得到的结果,找到结果中二进制第一次出现1的位置,记录下来,然后把这个位置是1的数字划分为第一的数组,对于这个位置的数字是0的数组,为第二个数组,进行异或,得到的两个数组就是我们所需要的。

class Solution {
public:
    void FindNumsAppearOnce(vector data,int* num1,int *num2) {
        if(data.size() < 2)
            return;
        unsigned int indexof1 = findFirstBit1(data);
        
        *num1 = 0;
        *num2 = 0;
        for(int i = 0; i < data.size(); i++){
            if(bitIs1(data[i], indexof1)){
                *num1 ^= data[i];
            }else{
                *num2 ^= data[i];
            }
        }
        
    }
    
    unsigned int findFirstBit1(vector data){
        int resultExclusiveOR = 0;
        for(int i = 0; i < data.size(); i++){
            resultExclusiveOR ^= data[i];
        }
        
        int indexBit1 = 0;
        while((resultExclusiveOR & 1) == 0 && (indexBit1 < 8*sizeof(resultExclusiveOR)))
        {
            resultExclusiveOR = resultExclusiveOR >> 1;
            indexBit1++;
        }
        return indexBit1;
    }
    
    bool bitIs1(int num, unsigned int indexBit1){
        num = num >> indexBit1;
        return (num & 1);
    }
};

你可能感兴趣的:(剑指offer:数组中只出现一次的数字)