题目:
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?
扫两遍,第一遍全异或得值temp。取temp中最低位不为0的位,其余位置0。如temp = 6 = 0x110,则取0x010。
扫第二遍,所有 i & 0x010 == 0x010的数异或得一个结果,其余数异或得另一个结果。
原理是两个不同的数至少会有一个bit位不同,造成全异或的结果中至少一位为1.那么以该位做区分,即可得两数。
C++版:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> result(2, 0);
int temp = 0;
for(auto i : nums)
temp ^= i;
int i = 1;
while((temp & i) != i)
i = i << 1;
for(auto j : nums) {
if((j & i) == i)
result[0] ^= j;
else
result[1] ^= j;
}
return result;
}
};
Java版:
public class Solution {
public int[] singleNumber(int[] nums) {
int[] result = new int[2];
int temp = 0;
for(int i = 0; i < nums.length; i++)
temp ^= nums[i];
int j = 1;
while((temp & j) != j)
j <<= 1;
for(int i = 0; i < nums.length; i++) {
if((nums[i] & j) == j)
result[0] ^= nums[i];
else
result[1] ^= nums[i];
}
return result;
}
}
Python版:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = [0, 0]
temp = 0
for i in nums:
temp ^= i
j = 1
while temp & j != j:
j <<= 1
for i in nums:
if i & j == j:
result[0] ^= i
else:
result[1] ^= i
return result