137. 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 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99
public class Solution {
    public int singleNumber(int[] nums) {
        int[]count = new int[32];
        int rst = 0;
        for(int i=0; i<32; i++){
            for(int j=0; j<nums.length; j++)
                count[i] += (nums[j] >> i) & 1;
            rst |= ((count[i] % 3)<<i);
        }
        return rst;
    }
}

https://cloud.tencent.com/developer/article/1131945

public int singleNumber(int[] A) {
    int ones = 0, twos = 0;
    for(int i = 0; i < A.length; i++){
        ones = (ones ^ A[i]) & ~twos;
        twos = (twos ^ A[i]) & ~ones;
    }
    return ones;
}

这个时候Python就比较尴尬了,需要判断第32位上面是不是1,如果是1,说明是负数,结果要减去2**32

class Solution:
    def singleNumber(self, a):
        """
        :type nums: List[int]
        :rtype: int
        """
        count=[0]*32
        for i in a:
            for j in range(32):
                count[j] += (i>>j) & 1
        
        res=0
        for i,v in enumerate(count): 
            if v%3==1:
                res+=(1<<i)
        return res if res<=2**31-1 else res-2**32
    
print(Solution().singleNumber([2,2,3,2]))
print(Solution().singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2]))

print(2**31)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值