题目:
思路+代码:
class Solution:
def singleNumbers(self, nums: List[int]) -> List[int]:
if not nums:
return []
# 思路:
# 1. 首先当a,b不相等时,全员异或的结果 == a ^ b,先得到全员异或结果
# 2. 选取全员异或结果的二进制的某一位1,则代表在这一位,a和b的异或结果不同
# 3. 遍历数组,分为两组:根据在2步骤上选出的目前是1的二进制位,一组 与1 异或==0;另一组与1 异或==1
# 4. 分别在这两组进行全员异或各得到一个不重复的数
res = functools.reduce(lambda x, y: x ^ y, nums)
div = 1
while (div & res) ==0:
div <<= 1
a, b = 0, 0
for each in nums:
if each & div:
a ^= each
else:
b ^= each
return [a,b]