[leetcode] 137. Single Number II 解题报告

题目链接:https://leetcode.com/problems/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?


思路:分别计算到当前位置出现一次的数, 出现两次的数, 出现三次的数(用于消除出现在一次和二次的结果中出现三次的数). 其中出现一次的数很好统计, 只要异或就行, 这样最后保留的就是出现奇数次的数. 统计出现两次的数就要看这个数之前是不是出现过, 也就是和出现一次的数按位与就行了. 统计出现三次的数就要他是不是出现奇数次, 并且至少出现了两次. 这样当我们统计好这三个量之后还要消除在出现one中出现三次的数, two中出现三次的数. 这样在one和two中剩下就是只出现一次和两次的数.

代码如下:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int one =0, two=0, three=0;
        for(auto val: nums)
        {
            two |= (val&one);
            one ^= val;
            three = (one&two);
            one ^= three;
            two ^= three;
        }
        return one;
    }
};


参考:http://www.cnblogs.com/daijinqiao/p/3352893.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值