解题思路:统计数组中所有数每一个比特位上的1加起来的个数,然后对3求余,就得到了只出现了一次的那个数的各个比特位上具体是0还是1
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = [0] * 31
for i in range(31):
tmp = 0
for x in nums:
tmp += (x >> i) & 1
# print(tmp)
res[i] = tmp % 3
ans = 0
# print(res)
for i in range(31):
if res[i]:
ans += (res[i]) << i
return ans
思路二:这个比较难想,我也是看的别人的思路:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
one, two = 0, 0
for x in nums:
one = one ^ x & ~two
two = two ^ x & ~one
return one