137. 只出现一次的数字 II
难度
中等
292
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99
字典
class Solution:
def singleNumber(self, nums: List[int]) -> int:
#a=list(set(nums))
n=len(nums)
dict_={}
for i in range(n):
dict_[nums[i]]=dict_.get(nums[i],0)+1
for j in list(dict_.keys()):
if dict_[j]==1:
return j
set()
class Solution:
def singleNumber(self, nums: List[int]) -> int:
#a=list(set(nums))
return (sum(set(nums))*3-sum(nums))//2
位运算
class Solution:
def singleNumber(self, nums: List[int]) -> int:
one=0
two=0
for num in nums:
one=one^num&~two
two=two^num&~one
return one
class Solution:
def singleNumber(self, nums: List[int]) -> int:
one=0
two=0
three=0
for num in nums:
two|=one&num
one=one^num
three=one&two
one=one&~three
two=two&~three
return one