我必须找到序列的主要元素:
92,19,19,76,19,21,19,85,19,19,19,94,19,19,22,67,83,19,19,54,59,1,19,19
一个主要元素是在集合中出现超过 size/2 倍的元素。
现在的问题是,在计数到 92 之后,它会从集合中删除值为 92 的所有元素,然后它会计算 19 的个数。这个序列中 19 的个数是 13,但计数算法是刚回来1。 计数算法仅针对序列的第一个元素返回正确答案。
函数如下:
int countMajor(vector<int>& v)
{
int max = (v.size() / 2);
int c = 0;
do{
c = count(v.begin(), v.end(), v[0]);
if (c > max)
return v[0];
v.erase(remove_if(v.begin(), v.end(), [&v](int i){
if (v[0] == i)
return true;
return false;
}), v.end());
} while (!v.empty());
return -1;
}
计数到 92 后,它将被删除,v[1]
即 19 将成为新的 v[0]
。
我无法弄清楚我做错了什么。
最佳答案
你正在删除 v[0]。
制作它:
int e = v[0];
v.erase(remove_if(v.begin(), v.end(), [e](int i){
if (e == i)
return true;
return false;
}), v.end());
关于c++ - STL 计数算法返回不正确的值。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23424422/