Single Number III
Question
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?
Tags
- Bit Manipulation
Thought
This problem is very similar to "Single Number", but there are two unique numbers in the array. xor
is still a reliable way but it will represent the result of the two unique numbers finally. By dividing these two unique numbers according to the highest position in the binary format, these two numbers can be extract easily.
Code
code comes from: https://discuss.leetcode.com/topic/30166/easy-python-o-n-o-1-solution
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor = 0
a = 0
b = 0
for num in nums:
xor ^= num
mask = 1
while(xor&mask == 0):
mask = mask << 1
for num in nums:
if num&mask:
a ^= num
else:
b ^= num
return [a, b]