2.1.23 Single Number
描述
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?
分析
描述
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?
分析
异或,不仅能处理两次的情况,只要出现偶数次,都可以清零。
异或运算符的特点是:数a两次异或同一个数b(a=a^b^b)仍然为原值a.
上述题目的解答可以如下所示:
class Solution {
public:
int singleNumber(int A[], int n) {
int x=A[0];
for(int i=1;i<n;++i){
x=x^A[i];
}
return x;
}
};