题目
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?
解析
要求不用额外内存,最好的方式就是用异或
class Solution {
public:
int singleNumber(vector<int>& nums) {
int x = 0;
for (size_t i = 0; i < nums.size(); ++i)
x ^= nums[i];
return x;
}
};