Given a non-empty 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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
这道题给我们一个数组,这个数组中除了一个数之外的其他数都出现了两次,让我们找出这个落单的数,想法就是利用一个哈希表,然后遍历数组,将出现两次的数先存放在表中,第二次遍历到时删除,最后留下来的就是我们需要的数。
C++
int singleNumber(vector<int>& nums) {
unordered_set<int> m;
for(int i = 0;i < nums.size();++i)
{
if(m.count(nums[i]))
m.erase(nums[i]);
else
m.insert(nums[i]);
}
return *m.begin();
}