Problem:
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?
Analysis:
解决方法是按(2进制或bit)位展开每一个数并相加。因为是除了一个元素以为,所有元素的出现都是3个。相加完毕,在例外元素bit值为1的那一位必定是3×k+1的形式,bit为0的那一位是3×k的形式。(k是某一个正整数)所以,模3以后剩下的值,再变成10进制,就是所要找的元素。
需要注意的是:按bit展开不需要预先做好。使用(A[i] >> j) & 1可以得到某个指定的展开位的值。
衍生问题:(a) every element appears k (k > 1) times except for one (b) every element appears a multiple of three times except for one, and the exceptional element appears once.
Solution:
C++:
int singleNumber(int A[], int n)
{
int bitArray[32] = {0};
int rval = 0;
for(int j = 0; j < 32; ++j) {
for(int i = 0; i < n; ++i)
bitArray[j] += (A[i] >> j) & 1;
rval |= ((bitArray[j] % 3) << j);
}
return rval;
}