class Solution:
def singleNumber(self, nums: List[int]) -> int:
cnt = [0] * 32
for i in range(32):
for x in nums:
if x & (1 << i):
cnt[i] += 1
ret = 0
for i, n in enumerate(cnt):
if n % 3:
ret += 2 ** i
return ret
优化:上述Python代码只能处理正数,如果是负数还要一步操作
Python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
cnt = [0] * 32
for i in range(32):
for x in nums:
if x & (1 << i):
cnt[i] += 1
ret = 0
for i, n in enumerate(cnt):
if n % 3:
ret += 2 ** i
if cnt[31] % 3 == 0: # 最高位是 0 为正数
return ret
else:
return ~(ret ^ 0xffffffff) # 这一步的操作实际上就是讲 ret 二进制表示中 32位以上的部分都置为 0
思路2:有限状态自动机
Python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ones, twos = 0, 0
for num in nums:
ones = ones ^ num & ~twos
twos = twos ^ num & ~ones
return ones