Given an array of integers, every element appears twice except for one. Find that single one.
Note:
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 result = 0;
for(int i = 0; i < nums.size(); i++) {
result ^= nums.at(i);
}
return result;
}
};