Single Number III

Description:

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?

Code:

    vector<int> singleNumber(vector<int>& nums) {
        vector<int>result;
        if (nums.size() < 2)
            return result;
        int xorAll = 0;
        for (int i = 0; i < nums.size(); ++i)
            xorAll^=nums[i];
        unsigned int x = 1;
        while ((xorAll & x) == 0)
        {
            x=x<<1;
        }
        int result1=0,result2=0;
        for (int j = 0; j < nums.size(); ++j)
        {
            if ((nums[j]&x) == 0)
                result1^=nums[j];
            else
                result2^=nums[j];
        }
        result.push_back(result1);
        result.push_back(result2);
        return result;
    }

PS:

思路很清晰,但是写代码的是后老在细节出错,主要是两个判断条件要注意

posted @ 2015-08-23 10:13  Rosanne  阅读(137)  评论(0编辑  收藏  举报