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?
思路:用变量分别存储出现一次、两次、三次的number
出现一次的number: 抑或操作去除了出现两次的可能,与未出现三次的number作“与操作”去除了出现三次的可能
出现两次的number:与出现一次的number作“与操作”
出现三次的number: 出现一次的number“与操作”出现两次的number
class Solution {
public:
int singleNumber(int A[], int n) {
int once = ;
int twice = ; for (int i = ; i < n; i++) {
twice |= once & A[i]; //the num appeared 2 times
once ^= A[i]; //the num appeared 1 times
int not_three = ~(once & twice); //the num not appeared 3 times
once = not_three & once; //remove num appeared 3 times from once
twice = not_three & twice; //remove num appeared 3 times from twice
}
return once;
}
};