SingleNumberII

来源:互联网 发布:临时用电计算软件 编辑:程序博客网 时间:2024/05/16 09:30

Description:
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?

分析:
方法 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 记录的是最终结果。

Code:

#include <iostream>using namespace std;//方法一,时间复杂度O(n),空间复杂度O(1)class Solution_1{public:    int singleNumber(int A[],const int n)    {        int bits = sizeof(int)*8;        int counts[bits];        fill_n(&counts[0],bits,0);        for (int i=0 ; i < n ; ++i)        {            for (int j=0 ; j < bits ; ++j)            {                counts[j] += (A[i]>>j) & 1;                counts[j] %= 3;            }        }        int result = 0;        for (int i=0; i < bits; ++i)        {            result += (counts[i]<<i);        }        return result;    }};//方法二,时间复杂度O(n),空间复杂度O(1)class Solution_2{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;    }};int main(){    const int n=7;    int A[n] = {2,3,4,3,2,3,2};    Solution_1 solution_1;    cout<<"方法一: ";    cout<<solution_1.singleNumber(A,n)<<endl;    Solution_2 solution_2;    cout<<"方法二: ";    cout<<solution_2.singleNumber(A,n)<<endl;    return 0;}

这里写图片描述

0 0
原创粉丝点击