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]
.
Analysis
This question is quite similar to the single number. except for for this question, there are two numbers appearing once.
My idea is from here http://bookshadow.com/weblog/2015/08/17/leetcode-single-number-iii/.
The idea is when we do the XOR of all numbers, the position that is 1 mean where the two numbers are different at this position, then we can use this position to divide the all numbers to two sets, then this question turns to single number 1.
This method would be faster than hash table, because it is pretty fast to do bit manipulation than build the object and so on.
Code
public class Solution {
public int[] singleNumber(int[] nums) {
int AorB = 0;
int length = nums.length;
for(int i = 0; i < length; i++){
AorB = AorB ^ nums[i];
}
int lowBit = AorB &((-1) * AorB);
int A = 0;
int B = 0;
for(int i = 0; i < length; i++){
if(nums[i] & lowBit == 0)
A = A ^ nums[i];
else
B = B ^ nums[i];
}
int[] result= new int[2];
result[0] = A;
result[2] = B;
return result;
}
}