leetcode 137. Single Number II

题目链接:leetcode

思路:
使用xor异或的性质可以常数空间复杂度解决问题。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ones = twos = threes= 0
for num in nums:
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
return ones
print(Solution().singleNumber([1,1,1,2,2,2,3]))