Problem
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.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
Algorithm
Use bineary proptertys. a^a = 0, a ^-a is the last 1 in bits.
Code
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
two = 0
for num in nums:
two ^= num
right = two & -two
one = 0
for num in nums:
if num & right:
one ^= num
return [one, two^one]