136. Single Number
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?
题意理解:
给定一个整数数组,每个元素出现两次,除了一个,找出这个元素。(线性运行时间复杂度,无额外内存)
首先想到的是遍历,两次for循环,太暴力,时间复杂度O(n2)。
参考http://www.cnblogs.com/fanyabo/p/4180800.html后,
解题思路关键:异或。(a^b=b^a, 0^a=a)
那么假设给定一个数组[2,3,4,4,3,2,1,5,1],
2^3^4^4^3^2^1^5^1=5
C++:
class Solution{
public:
int singleNumber(vector<int>& nums)
{
int ele=0;
for (int i = 0; i<nums.size(); i++)
{
ele ^= nums[i];
}
return ele;
}
};