您的位置:首页 > 其它

[LeetCode] Single Number II

2014-06-27 23:21 260 查看
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?

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

class Solution
{
public:
int singleNumber(int A[], int n)
{
vector<int> cnt;
int width = sizeof(int)*8;
cnt.resize(width, 0);
int res = 0;

for(int i  = 0; i< n; i++)
{
for(int j  = 0; j< width; j++)
{
cnt[j] += (A[i] >> j) & 0x1;
//cnt[j] %= 3;
}

}
for(int j  = 0; j< width; j++)
{
//cout << "j :\t" <<j <<"\t cnt\t"<< cnt[j]<<endl;
if(cnt[j]%3 != 0)
res ^=  ( 1 << j);
}
return res;
}
} ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: