题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/
难度:中等

描述:
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

题解

  1. class Solution:
  2. def singleNumbers(self, nums: List[int]) -> List[int]:
  3. ret_xor = 0
  4. for i in nums:
  5. ret_xor ^= i
  6. digit = 1
  7. while ret_xor & digit == 0:
  8. digit <<= 1
  9. p, q = [], []
  10. for i in nums:
  11. if i & digit == 0:
  12. p.append(i)
  13. else:
  14. q.append(i)
  15. ret = []
  16. temp = 0
  17. for i in p:
  18. temp ^= i
  19. ret.append(temp)
  20. temp = 0
  21. for i in q:
  22. temp ^= i
  23. ret.append(temp)
  24. return ret