Given an array, each number appears twice except one, find that single one.
First thinking is using Hash map, the key is each number and the value is their appearance times. This is a very intuitive thinking and easy to implemented.
<span style="font-size:14px;"> int singleNumber(vector<int>& nums) {
unordered_map<int,int> times;
int len=nums.size();
if(!len) return 0;
for(int i=0;i<len;i++)
{
auto sign=times.find(nums[i]);
if(sign!=times.end()) times[nums[i]]++;
else times[nums[i]]=1;
}
for(auto ite=begin(times);ite!=times.end();ite++)
{
if(ite->second==1) return ite->first;
}
}</span>
int singleNumber(vector<int>& nums) {
int len=nums.size();
int res=nums[0];
for(int i=1;i<nums.size();i++)
{
res=res^nums[i];
}
return res;
}
There are many ways like using an array to store a bool value. This problem is funny.