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?
用个现成的 unordered_map, 算是hash table, O(N) buildup O(1) look up
class Solution {
public:
int singleNumber(int A[], int n) {
unordered_map<int,int> myMap;
for (int i=0; i<n; i++)
{
if (myMap.count(A[i])==0)
myMap[A[i]]=i;
else
myMap.erase(A[i]);
}
return myMap.begin()->first;
}
};
如果不用额外buffer,放狗一搜,都是位操作。。。那玩意从来没明白过。有人说sort,不过sort 是NlgN. 没好哪里去。。。不过LEETCODE OJ能过。。。这也是奇葩的地方,呵呵。
class Solution {
public:
int singleNumber(int A[], int n) {
sort(A,A+n);
bool found=false;
int ind;
for (int i=0; i<=n/2;i++)
{
if (A[2*i]!=A[2*i+1])
{
found=true;
ind=2*i;
break;
}
}
if (found)
return A[ind];
else
return A[n-1];
}
};