题目
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
解题思路
位运算做法请参考博客
代码
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return (3 * sum(set(nums)) - sum(nums)) // 2
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for i in range(32):
ct = 0
for n in nums:
ct += (n >> i) & 1
res |= (ct % 3) << i
return res - 2**32 if res >> 31 & 1 else res
class Solution:
def singleNumber(self, nums: List[int]) -> int:
low = high = 0;
for n in nums:
low = (low ^ n) & ~high;
high = (high ^ n) & ~low;
return low