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?
思路:异或操作符有个这样一个性质:两个相同的数异或后结果为0,0^A = A,并且满足交换律。
比如 A^B^C^B 等价于 A^C。这一性质常用于寻找成对出现时,缺失的某一个数。
如果有一组数,A、B、C、A、B 则A^B^C^A^B = D,即D快速出现了一次。
使用异或操作符能够满足,此题要求的时间复杂度为O(n), 空间复杂度O(1)。
class Solution {
public:
int singleNumber(int A[], int n) {
int result = 0;
for (int i = 0; i < n; ++i) {
result ^= A[i];
}
return result;
}
};