Single Number II

Single Number II


Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?




这个是用ones 和 twos 分别表示两个bit,要实现计算3的倍数,这俩bit的变化规律是 (注意实际运算中A[ i ]就相当于1)

twos     ones
  0          0
  0          1
  1          0
  1          1
  0          0
当ones和twos都达到1时,用xthrees把他们都重置为0,这就是xthrees开始那三行的作用
那么前两行计数  他利用的规律是
第一行 计算twos : 当ones是0时,twos不变,(利用了 x|0==x) 当ones是1,twos变为1 ( ones 是1 twos 一定是0 而 0|x==x)
第二行 计算ones : 简单的xor,偶数次为0,奇数次为1
大概就是这么回事了

顺便贴个讨论里那个更简洁的代码  原理一样的


    public int singleNumber(int[] A) {
        int zeros=0, ones=0;
        for (int i=0; i<A.length; i++){  // 00 -> 01 -> 10 -> 00
            zeros = (zeros^A[i]) & ~ones;  // if bit1 is 1 we should put bit0 as 0, otherwise just count
            ones = (ones^A[i]) & ~zeros;  // if bit0 is 1 we should put bit1 as 0, otherwise just count
        }
        return zeros|ones;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值