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?
Solution1:
时间复杂度O(n) 空间复杂度O(n)
class Solution {
public:
int singleNumber(int A[], int n) {
map<int,int> m;
if(n<=0)
return 0;
else if(n==1)
return A[0];
for(int i=0;i<n;i++)
m[A[i]]++;
for(int i=0;i<n;i++)
{
if(m[A[i]]==1)
return A[i];
}
}
};
Solution2:
考虑数的性质,两个相同的数进行异或运算得到的结果是0
a^a=0;
0^a=a;
class Solution {
public:
int singleNumber(int A[], int n) {
int res=0;
for(int i=0;i<n;i++)
res=res^A[i];
return res;
}
};