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;
}
};
本文介绍了一种算法,用于在一个整数数组中找出仅出现一次的元素,所有其他元素都出现了三次。该算法使用了一个32个元素的容器来记录各个位上数字出现的次数,并最终通过位运算返回唯一的整数。
606

被折叠的 条评论
为什么被折叠?



