给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
样例
给出 [1,2,2,1,3,4,3],返回 4
挑战
原本的想法是利用hash表,将数陆续放入hash表中,一旦出现匹配则,删除hash表中的数,最后剩下的数就是返回值了。后来经过百度发现了更为简单的方法。
一次遍历,常数级的额外空间复杂度
利用位运算的性质,一个数与自身异或的结果为0,将整个数组与0异或,因为成对出现的数会彼此抵消,最后只剩下0与单独的数异或了。
class Solution {
public:
/**
* @param A: Array of integers.
* return: The single number.
*/
int singleNumber(vector<int> &A) {
// write your code here
int a =0;
for (auto ite = A.begin(); ite!=A.end();ite++){
a ^= *ite;
}
return a;
}
};