**
题目:
**
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?
Subscribe to see which companies asked this question
大意:有一组数字,除了一个元素只出现一次,其他每个元素都会出现两次,找出这个元素。时间复杂度要求是O(n),空间复杂度要求O(1)
算法分析:
这个题若没有空间复杂度的要求很容易就能想到怎么做,比如直接循环一遍统计每个数字出现多少次用map存起来,然后找出只出现一次的就可以搞定了,事实上这样做在leetcode上也可以AC,但是并不符合题意,因为这样做时间复杂度和空间复杂度都是O(n)。
其实这个题考察是的异或运算符“^”的使用,由于只有一个数字出现一次,其他都出现两次,只要把所有数字都进行异或操作,显然出现两次的数字会自动抵消,剩下最后的结果就是只出现了一次的数字。这样时间复杂度为O(n),空间复杂度为O(1)
代码实现如下:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
int result = nums[0];
for(int i=1; i<n; ++i)
result ^= nums[i];
return result;
}
};