您的位置:首页 > 其它

LEETCODE: Single Number II

2015-01-06 23:02 176 查看
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?

用一个32个元素的容器记录各个位上数字出现的记录!

class Solution {
public:
int singleNumber(int A[], int n) {
vector<int> bits(32);
int result = 0;
for(int ii = 0; ii < n; ii ++) {
// Check every bit of A[ii]
int base = 1;
for(int jj = 0; jj < 32; jj ++) {
int temp = A[ii] & base;
if(temp != 0) {
bits[jj] ++;
}
base = base << 1;
}
}

for(int ii = 0; ii < 32; ii ++) {
if(bits[ii] % 3 == 1)
result |= 1 << ii;
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LEETCODE 算法