260. Single Number III

来源:互联网 发布:公司注册淘宝店 编辑:程序博客网 时间:2024/06/04 19:00
问题:

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
分析:问题中只有两个数是出现一次的。

1. 第一个pass: 把数组里面所有的数都xor起来,会得到单独的两个数的xor结果,相同的元素xor结果是0,和0 xor的结果是这个数本身,因为单独的两个数彼此之间是不相同的,所以一定有一些数位上的数是不同的,xor的结果这位上就是1.

    xor = ~(xor - 1) 能够找到两个数里面最右的一个不同的数位

2. 第二个pass:对于数组里面的所有的数,和那个最右不同的数位xor,不同的那两个单独的数一定会被分到不同的组,然后对两个组内部再xor一次,就能得到结果:如果结果是0时,也就是说这一位上是设置了的那个,和res[0] xor,否则, 和res[1] xor。


代码:

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int r = 0, n = nums.size(), i = 0, last = 0;
        vector<int> ret(2, 0);
        
        for (i = 0; i < n; ++i) 
            r ^= nums[i];
        
        last = r & (~(r - 1));
        for (i = 0; i < n; ++i)
        {
            if ((last & nums[i]) != 0)
                ret[0] ^= nums[i];
            else
                ret[1] ^= nums[i];
        }
        
        return ret;
    }
};

原创粉丝点击