题目描述
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?
class Solution {
public:
int singleNumber(int A[], int n) {
int one=0; //记录某一位,1只出现一次时为1.
int two=0;//记录某一位,1只出现两次时为1;
int three;//记录某一位,1只出现3次时为1;
for(int i=0;i<n;++i)
{
two|=one&A[i]; //如果1只出现了一次,并且这次又为1,则two为1,如果1上次出现,这次没出现则two保持原来的状态。
one^=A[i]; //如果1又出现了,证明不是只出现1次,要置0.之后重新统计
three=one&two;//只出现一次,并且又出现了一次,证明出现了3次。
one&=~three;//将出现3次1的位置置零
two&=~three;
}
return one;
}
};