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.

Example:

Input:  [1,2,1,3,2,5]
Output: [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:异或

1.异或所有元素

2.求得异或值最右边第一为1的位

3.用2的结果将所有元素划分为两个组,(要求的两个数就分别在这两个组中)

4.每个组分别异或

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        vector<int> res(2,0);
        if(nums.size()<2) return res;
        int xorNum=0;
        for(int a:nums) xorNum^=a;
        xorNum=xorNum&(~(xorNum-1));//从右往左第一位不同的,以此将nums划分为两个组(主要是将两个单独的数分到两组中)
        for(int a:nums){
            if((a & xorNum)!=0) res[0]^=a;
            else res[1]^=a;
        }
        return res;    
    }
};

方法2:利用set(非常量个空间)

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        set<int> inp;
        vector<int> res;
        for(int a:nums){
            if(!inp.count(a)){
                inp.insert(a);
            }else{
                inp.erase(a);
            }
        }
        for(int a:inp){
            res.push_back(a);
        }
        return res;
    }
};

 

点赞