您的位置:首页 > 其它

LeetCode: Single Number II

2014-05-08 00:00 411 查看
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?
本题和上一题 Single Number 考察的是位运算。

方法 1:创建一个长度为 sizeof(int) 的数组 count[sizeof(int)],count[i] 表示在在 i 位出现的 1 的次数。如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。

方法 2:用 one 记录到当前处理的元素为止,二进制 1 出现“1 次”(mod 3 之后的 1)的有哪些二进制位;用 two 记录到当前计算的变量为止,二进制 1 出现“2 次” (mod 3 之后的 2)的有哪些二进制位。当 one 和 two 中的某一位同时为 1 时表示该二进制位上 1 出现了 3 次,此时需要清零。即用二进制模拟三进制运算。最终 one 记录的是最终结果。
方法 1,时间复杂度 O(n),空间复杂度 O(1)

// LeetCode, Single Number II
// 方法 1,时间复杂度 O(n),空间复杂度 O(1)
class Solution {
    public:
        int singleNumber(int A[], int n) {
            const int W = sizeof(int) * 8; // 一个整数的 bit 数,即整数字长
            int count[W]; // count[i] 表示在在 i 位出现的 1 的次数
            fill_n(&count[0], W, 0);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < W; j++) {                     
                    count[j] += (A[i] >> j) & 1;
                    count[j] %= 3;
                }
            }
            int result = 0;
            for (int i = 0; i < W; i++) {
                result += (count[i] << i);
            }
            return result;
        }
};

方法 2,时间复杂度 O(n),空间复杂度 O(1)

// LeetCode, Single Number II
// 方法 2,时间复杂度 O(n),空间复杂度 O(1)
class Solution {
    public:
        int singleNumber(int A[], int n) {
            int one = 0, two = 0, three = 0;
            for (int i = 0; i < n; ++i) {
                two |= (one & A[i]);
                one ^= A[i];
                three = ~(one & two);
                one &= three;
                two &= three;
            }
            return one;
        }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: