[LeetCode] Single Number III

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:

  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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解題思路:

題意爲給定一個整數數組,其中有兩個數只出現一次,其餘數出現兩次。要求線性時間、常量空間找出這兩個數。

我們知道,兩個相等的數異或結果爲0。因此,首次掃描數組,得到兩個單獨的數A、B的異或結果AxorB。因爲A和B不相等,因此AxorB一定不爲0,且二進制位爲1的位A和B一定不同。任取AxorB中的一個二進制位,可以將原數組元素分成兩組異或即得結果。

注意n&(~(n-1))表示取的n中的最後一位二進制位。

另外,&的優先級小於==的優先級。

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int len = nums.size();
        int AxorB = 0;
        for(int i=0; i<len; i++){
            AxorB ^= nums[i];
        }
        int mask = AxorB & (~(AxorB-1));
        int A = 0;
        int B = 0;
        for(int i=0; i<len; i++){
            if((mask&nums[i])==0){
                A ^= nums[i];
            }else{
                B ^= nums[i];
            }
        }
        return vector<int>({A, B});
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章