首页 > 其他 > 详细

137. Single Number II (Bit)

时间:2015-12-06 09:53:55      阅读:165      评论:0      收藏:0      [点我收藏+]

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?

思路:

Step1:从Single Number我们知道,通过易或操作可以用一个int存储出现过单数次的

Step2:我们可以通过与单数出现的做与,来获得出现过双数次的数

Step3:想办法把Step1 int中出现三次的去掉。

class Solution {
public:
    int singleNumber(int A[], int n) {
        int once = 0;  
        int twice = 0;  
  
        for (int i = 0; i < n; i++) {  
            twice |= once & A[i]; //the num appeared 2 times  
            once ^= A[i];  //the num appeared 1 times
            int not_three = ~(once & twice);  //the num not appeared 3 times
            once = not_three & once;  //remove num appeared 3 times from once
            twice = not_three & twice;  //remove num appeared 3 times from twice
        }  
        return once;  
    }
};

 

137. Single Number II (Bit)

原文:http://www.cnblogs.com/qionglouyuyu/p/5022845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!