137. 只出现一次的数字||(位运算)

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值