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?
这道题和上一道都可以用map来解决。只是空间消耗比较大。
ANS:
class Solution {
public:
int singleNumber(int A[], int n) {
int sum;
int ans = 0;
for (int i = 0;i < 32;i ++)
{
const unsigned int mask =1 <<i;
sum = 0;
for (int j = 0;j < n;j ++)
{
sum += (A[j]&mask)>0?1:0;
}
ans |= (sum%3)>0?mask:0;
}
return ans;
}
};