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:
int singleNumber(int A[], int n)
{
int res = 0;
for (int i = 0; i < 32; i++)
{
int val = 0;
for (int j = 0; j < n; j++)
{
val += (A[j] >> i & 1);
}
val = val % 3;
if (1 == val)
res |= 1<<i;
}
return res;
}
};
本文介绍了一种算法,该算法能在O(n)的时间复杂度内从一个除了一个元素只出现一次外其余元素均出现三次的整数数组中找出那个唯一的元素。此算法巧妙地利用位操作来实现,避免了额外的空间开销。
408

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



