题目描述
现在有一个整数类型的数组,数组中素只有一个元素只出现一次,其余的元素都出现两次。
注意:
你需要给出一个线性时间复杂度的算法,你能在不使用额外内存空间的情况下解决这个问题么?
示例1
输入
[1,0,1]
返回值
0
一、 map<int,int>实现
代码
class Solution {
public:
/**
*
* @param A int整型一维数组
* @param n int A数组长度
* @return int整型
*/
int singleNumber(int* A, int n) {
// write code here
map<int, int> mapp;
for(int i=0;i<n;i++){
mapp[A[i]]++;
}
map<int, int>::iterator iter;
for(iter = mapp.begin();iter != mapp.end();iter++){
if(iter->second==1){
return iter->first;
}
}
}
};
二、 异或实现
因为每个元素只出现一次或两次,且两个相同的数异或值为0,任何数和0异或值为它本身 因此对每个值进行异或最后值即为答案
class Solution {
public:
/**
*
* @param A int整型一维数组
* @param n int A数组长度
* @return int整型
*/
int singleNumber(int* A, int n) {
// write code here
int res = 0;
for(int i=0;i<n;i++){
res ^= A[i];
}
return res;
}
};
个人觉得用map<int,int>比较好,当元素个数>2时,异或就无用武之地了。