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;
}