题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/
难度:中等
描述:
一个整型数组 nums
里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
题解
class Solution:
def singleNumbers(self, nums: List[int]) -> List[int]:
ret_xor = 0
for i in nums:
ret_xor ^= i
digit = 1
while ret_xor & digit == 0:
digit <<= 1
p, q = [], []
for i in nums:
if i & digit == 0:
p.append(i)
else:
q.append(i)
ret = []
temp = 0
for i in p:
temp ^= i
ret.append(temp)
temp = 0
for i in q:
temp ^= i
ret.append(temp)
return ret