您的位置:首页 > 其它

[Leetcode]Single Number II

2015-09-22 14:34 295 查看
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?

class Solution {
public:
/*algorithm: bit operation
just like binary op, count bit count and %3
time O(n) space O(1)
*/
int singleNumber(vector<int>& nums) {
int bit[32]={0};
for(int i = 0;i < nums.size();i++){
int n = nums[i];
for(int k = 0;k < 32;k++){
bit[k] += n&0x1;
bit[k] %= 3;
n >>= 1;
}
}
int ret = 0;
for(int k = 0;k < 32;k++)
ret |= bit[k] << k;
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法