题目地址
https://leetcode.com/problems/single-number-ii/
第一种方法,简单使用字典计数
返回出现次数为1的数即可
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
d = dict()
for i in nums:
d[i] = d.get(i, 0) + 1
for i in d:
if d[i] != 3:
return i
第二种方法,求和法
使用set将数组中的数字过滤为只出现一次,则set中的数字的和的三倍减去数组中的数字的和的结果是所求数字的二倍,将结果除以2即可,使用整除,获得结果为整数
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = set(nums)
return (sum(s) * 3 - sum(nums)) // 2
第三种,使用位计算
构造真值表
参考
https://blog.csdn.net/yutianzuijin/article/details/50597413
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
low = 0
high = 0
for i in nums:
low = ~high & (low ^ i)
high = ~low & (high ^ i)
return low