题目描述:
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异或的结果保持不变,
所以对输入数组中的所有元素异或,异或的结果即为只出现一次的元素。
AC代码如下:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int i = 0; i < nums.size(); ++i) ans ^= nums[i];
return ans;
}
};