您的位置:首页 > 其它

LeetCode | Single Number II

2013-12-20 11:18 399 查看


题目:

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?


思路:

一个比较好的方法是从位运算来考虑。每一位是0或1,由于除了一个数其他数都出现三次,我们可以检测出每一位出现三次的位运算结果再加上最后一位即可。


代码:

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ones = 0, twos = 0, threes = 0;
        for(int i = 0; i < n; i++)
        {
            threes = twos & A[i]; //已经出现两次并且再次出现
            twos = twos | ones & A[i]; //曾经出现两次的或者曾经出现一次但是再次出现的
            ones = ones | A[i]; //出现一次的
            
            twos = twos & ~threes; //当某一位出现三次后,我们就从出现两次中消除该位
            ones = ones & ~threes; //当某一位出现三次后,我们就从出现一次中消除该位
        }
        return ones; //twos, threes最终都为0.ones是只出现一次的数
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: