Single Number II

Single Number II

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example

Input: [2,2,3,2]
Output: 3
Input: [0,1,0,1,0,1,99]
Output: 99

Solution

弱智解法:
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = []
        if len(nums)==1:
            return nums[0]
        for i in range(len(nums)):
            judge = nums.pop()
            if(judge in nums or judge in res):
                res.append(judge)
                continue
            else:
                return judge
class Solution(object):
    def singleNumber(self, nums):
        one = 0
        two = 0
        three = 0
        for i in range(0,len(nums)):
            two |= one & nums[i] #当新来的为0时,two = two | 0,two不变,当新来的为1时,(当one此时为0,则two = two|0,two不变;当one此时为1时,则two = two | 1,two变为1
            one ^= nums[i]       #新来的为0,one不变,新来为1时,one是0、1交替改变
            three = one & two    #当one和two为1是,three为1(此时代表要把one和two清零了)
            one &= ~three        #把one清0
            two &= ~three        #把two清0
        return one
Resource: https://www.jianshu.com/p/758e799614b2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值