题目描述:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,3,2] 输出: 3
示例 2:
输入: [0,1,0,1,0,1,99] 输出: 99
解法1。利用数学,见下
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
nums_uni = list(set(nums))
supposed_sum = sum(nums_uni)*3
res = (supposed_sum - sum(nums))//2
return res
解法2。按位检查,查看所有数该位上为1的个数,这个个数肯定是3的倍数或者3的倍数+1,所以除3取余后就是target数在该位上是否为1的结果,如此下来,32位上是否为1的结果拼凑起来就可以还原该数。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
res = 0
for i in range(32):
mask = 1<<i
summ = 0
for n in nums:
if n&mask:
summ += 1
res |= (summ%3)<<i
return res if res < 2**31 else res-2**32 # 若输入是负数,所以需要进行范围检查
解法3。这种解法效率很高,真费解,还没懂,下面这篇博客有讲解,好像是涉及状态机的知识
https://blog.csdn.net/Koala_Tree/article/details/80228525
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
a, b = 0, 0
for n in nums:
b = (b^n) & ~a
a = (a^n) & ~b
return b