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?

本题最好理解版本

有的数字出现3次,个别出现1次,因此每出现3次就可以归零了。

我们用三个量分别记录出现1次、2次、3次(其实就是0次)的位,分别为x1,x2,x3.

某一位出现1次,可能之前出现过1次此次的数该位没出现,或者之前出现过3次,该次的数也出现过一次。

某一位出现2次,可能之前出现过1次此次的数该位出现1次,或者之前出现过2次,该次的数未出现。

某一位出现3次,可能之前出现过3次此次的数该位没出现,或者之前出现过2次,该次的数也出现过一次。

由于针对每个位出现几次是要按顺序计算的,一定要注意每次运算时必须用上次的量。

class Solution {
public:
    int singleNumber(int A[], int n) {
        if(A == NULL)return 0 ;
        int x0 = ~0;
        int x1 = 0;
        int x2 = 0;
        for(int i = 0 ; i < n;i++)
        {
            int t = x2;
            x2 = (x1 & A[i]) |(x2 & ~A[i]);
            x1 = (x0 & A[i]) |(x1 & ~A[i]);
            x0 = (t & A[i]) |(x0 & ~A[i]);
        }
        return x1;
    }
};

  

posted on 2014-03-26 21:45  pengyu2003  阅读(179)  评论(0编辑  收藏  举报

导航