Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
int singleNumber(int A[], int n) {
while(n>1)//共需进行n-2次异或
{
A[n-2] = A[n-1]^A[n-2];
n--;
}
return A[0];
}
//本题参看其他人的答案,或多多少利用了额外的变量!不知是否判断在O(1)复杂度即可!
如下:
int singleNumber(int A[], int n) {
int x = A[0];
for (int i = 1; i < n; ++i)
x ^= A[i];
return x;
}
有本题联想到一个交换不利用额外空间的例子
void swap(int &a, int &b)
{
a = a^b;//右边表达式都是一样
b = a^b;
a = a^b;
}
a=(a^b)^a;
b=(a^b)^b;
异或性质
1、交换律
2、结合律(即(a^b)^c == a^(b^c))
3、对于任何数x,都有x^x=0,x^0=x
4、自反性 A XOR B XOR B = A xor 0 = A