使用异或操作可以解决数字重复的问题,设置出现两次就归0,就像开了一局消消乐。
注意:这是默认使用多个不同数字可以无顺序的对一个地址进行异或,最终结果不变。
for(int i = 1; i<n; i++){
A[0] ^= A[i];
题目升级
这个解法和上面的一样,只不过开了三个地址(开了三局消消乐)。
ones这局仍然使用异或。 twos这局使用ones的结果操作,保证有两个数字一样的时候把那个数字存下来。
第三局threes 使用ones和twos的结果,保证三个数字一样的时候把那个数字存下来。如下图 取 t=4时的三者结果。
完整代码
class Solution {
public:
int singleNumber(int A[], int n) {
int ones = 0;
int twos = 0;
int threes = 0;
for(int i= 0;i<n;i++){
twos |= ones & A[i]; //update twos
ones ^= A[i]; //update ones
threes = ones & twos; //update threes
//这两步是当三次成功出现之后,把ones和twos再次置零,彻底去掉这个数字的对结果的影响
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
};
这里同一个数字(4)三次进入后变量的值。