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?
大意:给定一个数组,除了一个元素,其它每个元素都出现了两次,找出这个出现一次的元素。时间复杂度O(n), 空间复杂度O(1).
由于数组中除一个元素外 其他元素都出现了2次,因此出现偶数次的元素异或(即二进制模2加)后为0, 因此所以元素异或后即得到只出现一次的数字!
class Solution {
public:
int singleNumber(vector<int>& nums) {
int sum=0;
for(int i=0;i<nums.size();i++)
{
sum = sum ^ nums[i];
}
return sum;
}
};