题目链接:https://leetcode-cn.com/problems/single-number-iii/
难度:中等

描述:
给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。

进阶:你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?

题解

  1. class Solution:
  2. def singleNumber(self, nums: List[int]) -> List[int]:
  3. ans = 0
  4. for num in nums:
  5. ans ^= num
  6. ans &= -ans
  7. ans1 = ans2 = 0
  8. for num in nums:
  9. if num & ans:
  10. ans1 ^= num
  11. else:
  12. ans2 ^= num
  13. return [ans1, ans2]