260. Single Number III(重)

2017-02-21  本文已影响0人  殷水臣

这道题也很有意思,依旧是位运算,找出两个不一样的数,全部异或起来得到的是两个不同数的异或结果,此时为1的位就代表着这两数在这一位的值不同,那么就可以把原来的数组利用这一点分为两类:这一位是1和这一位是0的,再利用构造出来的只有这一位是1的数去与就可以分开各自异或各自的就行。

他人解法

很惭愧,完全没思路> <

class Solution
{
public:
    vector<int> singleNumber(vector<int>& nums) 
    {
        // Pass 1 : 
        // Get the XOR of the two numbers we need to find
        int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
        // Get its last set bit
        diff &= -diff;

        // Pass 2 :
        vector<int> rets = {0, 0}; // this vector stores the two numbers we will return
        for (int num : nums)
        {
            if ((num & diff) == 0) // the bit is not set
            {
                rets[0] ^= num;
            }
            else // the bit is set
            {
                rets[1] ^= num;
            }
        }
        return rets;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读