您的位置:首页 > 其它

LeetCode:Single NumberⅡ

2015-07-14 09:52 363 查看
Problems:

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(vector<int>& nums) {

const int N=sizeof(int)*8;

int count
;
fill_n(&count[0],N,0);

for(int i=0;i<nums.size();i++)
for(int j=0;j<N;j++)
{
count[j]+=(nums[i]>>j)&1;
count[j]%=3;
}
//返回结果
int result=0;

for(int j=0;j<N;j++)
result+=(count[j]<<j);
return result;

}
};


The second solution is need update.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: