码迷,mamicode.com
首页 > 其他好文 > 详细

137. Single Number II (Bit)

时间:2015-12-06 09:55:12      阅读:136      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!