-
题目:
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? -
idea:
- 当某一位出现三次时约掉
- 用two代表只出现过两次的位,one代表只出现过一次的位,appr代表需要约掉的位
- 在two与A[i]同时出现的位要约掉,即appr = two & A[i]
- 在one和A[i]同时出现的位要成为two,two除掉约去的位(即two ^ appr)也继续是two
- A[i]除去约掉的位(即A[i] ^ appr)成为one的候选者,将候选者与one异或即得迭代后的one。
- 遍历完以后,one即为只出现过一次(出现三次的都约掉了)的位,此时one即为只出现过一次的数。
-
code
class Solution {
public:
int singleNumber(int A[], int n) {
if (n == 1) return A[0];
if (n < 4) return -1;
unsigned two=0, one=0, appr = 0;
for (int i = 0; i < n; i++){
appr = two & A[i]; //在two与A[i]同时出现的位要约掉
two = (one & A[i]) | (two ^ appr); //在one和A[i]同时出现的位要成为two,two中出现appr(约掉)中没出现的位也要成为two
one = one ^ A[i] ^ appr; //A[i]中出现appr中没出现的位成为one的候选者,将候选者与one异或即得迭代后的one。
}
return one;
}
};