Thursday, December 8, 2016

Single Number III -- LeetCode

[Question]
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?
[Analysis]
By XOR all the elements, we can get the XOR result of the two single elements {A,B}. Since A!=B, there must one bit different between A and B. Therefore, divide all elements into two sets based on the bit value. XOR each set will give the two elements separately.

[Solution]
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int sum = accumulate (nums.begin(), nums.end(), 0, bit_xor<int>());
        int diff = sum & (-sum);
       
        vector<int> res = {0,0};
        for (auto n: nums) {
            if (n & diff) res[0]^=n;
            else res[1]^=n;
        }
        return res;
    }

};

No comments:

Post a Comment