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?
对于这道题,我不知道别人怎么做的,因为前两天刚看了STL中的map,觉得用map来做很简单,一次性就通过了(或许有点大材小用了吧),具体代码如下:
class Solution {
public:
int singleNumber(int A[], int n) {
map<int,int> arr;
for (int i = 0;i<n;i++)
{
if(arr.empty()) //将第一个数据插入
arr.insert(pair<int,int>(A[i],i));
else
{
if(arr.find(A[i])!=arr.end()) //如果先前已经插入了这样一个值,那么就从map中删除
{
arr.erase(A[i]);
}
else //如果先前没有插入了这样一个值,那么就添加到map中
arr.insert(pair<int,int>(A[i],i));
}
}
int result = arr.begin()->first; //重复的都被删除了,剩下的就只有一个单数
return result;
}
};
本文介绍了一种使用C++ STL中的map来找出整数数组中唯一出现一次的元素的方法,并提供了一个具体的实现示例。
711

被折叠的 条评论
为什么被折叠?



