Monday, August 17, 2015

LeetCode [260] Single Number III

 260. Single Number III

Medium

Given an integer array 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. You can return the answer in any order.

Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

 

Example 1:

Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation:  [5, 3] is also a valid answer.

Example 2:

Input: nums = [-1,0]
Output: [-1,0]

Example 3:

Input: nums = [0,1]
Output: [1,0]

 

Constraints:

  • 1 <= nums.length <= 30000
  •  Each integer in nums will appear twice, only two integers will appear once.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//C++: 20ms
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
        diff &= -diff;
        vector<int> ret(2);
        for(int n:nums){
            if(diff & n){
                ret[0] ^= n;
            }else{
                ret[1] ^= n;
            }
        }
        return ret;
    }
};
//Java
class Solution {
    public int[] singleNumber(int[] nums) {
        int diff = 0;
        for(int n:nums) diff ^= n;
        int setBit = diff & -diff;
        
        int[] ret = new int[2];
        for(int n:nums){
            if((n&setBit) == 0){
                ret[0] ^= n;
            }else{
                ret[1] ^= n;
            }
        }
        
        return ret;
    }
}

No comments:

Post a Comment