问题描述
在大小为2N的数组A中有N+1个不同的元素, 其中有一个元素重复了N次
返回重复了N次的哪个元素
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
unordered_map<int, int> um;
int n = A.size() / 2;
for (auto & e : A)
{
um[e]++;
}
for (auto & e : um)
{
if (e.second == n)
{
return e.first;
}
}
return -1;
}
};
第二种方法
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
set<int> s;
pair<set<int>::iterator, bool> p;
for (auto & i : A)
{
p = s.insert(i);
if (p.second == false)
{
return i;
}
}
return -1;
}
};
set.insert() 的返回值为 pair<set::iterator, bool>
插入失败即为出现重复数字