描述
整型數組中除一個元素外其它元素都重複出現 n 次,找出落單的元素,需保證時間複雜度在 O(n) 之內。算法
考慮 n = 2, n = 3 的情形;
考慮除了一個元素出現 m 次,其它元素出現 n 次的情形, 其中 m != n。數組
示例:
給定數組 array = [1, 1, 1, 11, 11, 3, 3, 3, 4, 4, 4], 因此 m=2, n=3, 查找到目標元素爲 11。spa
/* * @param array 目標數組 * @param len 數組元素個數 * @param n 普通元素出現次數 * @return 查找到的特殊出現次數的元素值 * */ int find(int array[], int len, int n) { int ret = 0; for (int i=0, tmp = 0; i<32; ++i, tmp=0) { for (int j=0; j<len; ++j) { tmp += (array[j] >> i) & 0x01; } ret |= !!(tmp % n) << i; } return ret; }
將目標數組分解爲二進制矩陣後進行組合。
==> 數組中各元素 [0-31] 位累加code
==> 累加和取餘普通元素出現次數blog
==> 非0值轉化爲1it
==> 轉換爲 int
11class