260. Single Number III

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:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Analysis:
主要还是涉及位运算,具体参见http://bookshadow.com/weblog/2015/08/17/leetcode-single-number-iii/
中间一步是找出xor的第一个为1的位,这个方法有很多。
Source Code(C++):

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        if (nums.size()<2) {
// return ;
        }
        int xor_nums=0;
        for(int i=0; i<nums.size(); i++) {
            xor_nums ^= nums.at(i);
        }
// int lastBit = xor_nums & -xor_nums;
        int lastBit = xor_nums - (xor_nums & (xor_nums-1));
        int a=0, b=0;
        for(int i=0; i<nums.size(); i++) {
            if ((lastBit&nums.at(i)) == 0) {
                a ^= nums.at(i);
            } 
            else {
                b ^= nums.at(i);
            }
        }
        vector<int> v;
        v.push_back(a);
        v.push_back(b);
        return v;
    }
};

int main() {
    vector<int> v1;
    vector<int> v2;
    Solution sol;
    v2 = sol.singleNumber(v1);
    return 0;
}

你可能感兴趣的:(260. Single Number III)