Leet Code: 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?

解法

如果使用辅助空间做的话就比较简单了,可以用unordered_map来统计每个整数出现的次数,然后扫描一遍这个unordered_map即可。但是题目要求的辅助空间是O(1),就不能在借助hash来实现,这里用到了位操作,解法如下:

将数组中的int型整数均表示成2进制形式,int型有32位,以其中任一位为例,累加统计该位 1出现的次数x,如果xmod3>0 ,说明要求的这个Single Number的改为为1,否则为0。我们可以为每位使用一个统计量来保存出现的次数,这个统计量能表示1出现1,2,3次(3次也就是0次)3种状态,type count[32],这可以通过3个int型变量实现,int one,two,three,分别表示出现1次、2次、3次,在遍历数组统计状态的时候,确保每位只处于某一状态。

代码

class Solution {
public:
int singleNumber(int A[], int n) {
        // Note: The Solution object is instantiated only once.
        //可以将one,two,three看成是某一位,然后再扩展到32位
        int one=0;
        int two=0;
        int three=0;
        for(int i=0;i<n;++i){
            three=two&A[i];//出现3次=出现2次&再次出现
            two=two|(one&A[i]);//计算出来的two包括了出现2次和出现3次的情况
            one=(one|A[i])&~two;//如果该位处于出现两次或三次的状态,那么该位出现一次的状态为0
            two=two&~three;//如果该位处于出现三次的状态,那么该位出现两次的状态为0
        }
        return two!=0?two:one;
    }
};


你可能感兴趣的:(code,number,number,single,single,II,Leet,出现一次的数)