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?

  • idea:

    1. 当某一位出现三次时约掉
    2. 用two代表出现过两次的位,one代表出现过一次的位,appr代表需要约掉的位
    3. 在two与A[i]同时出现的位要约掉,即appr = two & A[i]
    4. 在one和A[i]同时出现的位要成为two,two除掉约去的位(即two ^ appr)也继续是two
    5. A[i]除去约掉的位(即A[i] ^ appr)成为one的候选者,将候选者与one异或即得迭代后的one。
    6. 遍历完以后,one即为只出现过一次(出现三次的都约掉了)的位,此时one即为只出现过一次的数。
  • code

class Solution {
public:
    int singleNumber(int A[], int n) {
        if (n == 1) return A[0];
        if (n < 4) return -1;
        unsigned two=0, one=0, appr = 0;
        for (int i = 0; i < n; i++){
            appr = two & A[i]; //在two与A[i]同时出现的位要约掉
            two = (one & A[i]) | (two ^ appr); //在one和A[i]同时出现的位要成为two,two中出现appr(约掉)中没出现的位也要成为two
            one = one ^ A[i] ^ appr; //A[i]中出现appr中没出现的位成为one的候选者,将候选者与one异或即得迭代后的one。
        }
        return one;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值