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?
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Analysis:
Count the numbers of each bit for all integers and the bit which is not times of 3 is the bit of the integer appears once.
class Solution {
public:
int singleNumber(int A[], int n) {
vector<int> nums(32,0);
for(int i=0; i<n; i++)
{
int num = A[i];
for(int j=0; j<32;j++)
{
nums[j] += (num >> j) & 0x1;
}
}
int ret = 0;
for(int i=0; i<32;i++)
{
if (nums[i] % 3)
ret = ret | (0x1 << i);
}
return ret;
}
};
No comments:
Post a Comment