You are 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.
Example 1:
Input: nums = [1,1,2,3,2,4]
Output: [3,4]Example 2:
Input: nums = [2,1]
Output: [2,1]Example 3:
Input: nums = [-50,1,2,3,3,2,1,10]
Output: [-50,10]Constraints:
2 <= nums.length <= 30,000(-(2^31)) <= nums[i] <= ((2^31)-1)nums will appear twice, only two integers will appear once.class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
n, res = len(nums), []
for i in range(n):
flag = True
for j in range(n):
if i != j and nums[i] == nums[j]:
flag = False
break
if flag:
res.append(nums[i])
if len(res) == 2:
break
return resclass Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
count = {}
for num in nums:
count[num] = 1 + count.get(num, 0)
return [k for k in count if count[k] == 1]class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
seen = set()
for num in nums:
if num in seen:
seen.remove(num)
else:
seen.add(num)
return list(seen)class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
res, n = [], len(nums)
nums.sort()
for i in range(n):
if ((i > 0 and nums[i] == nums[i - 1]) or
(i + 1 < n and nums[i] == nums[i + 1])):
continue
res.append(nums[i])
return resclass Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
xor = 0
for num in nums:
xor ^= num
diff_bit = 1
while not (xor & diff_bit):
diff_bit <<= 1
a = b = 0
for num in nums:
if diff_bit & num:
a ^= num
else:
b ^= num
return [a, b]class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
xor = 0
for num in nums:
xor ^= num
diff_bit = xor & (-xor)
a = b = 0
for num in nums:
if diff_bit & num:
a ^= num
else:
b ^= num
return [a, b]