这是算法 http://www.cs.utexas.edu/~moore/best-ideas/mjrty/example.html 这是我的代码
#include <iostream>
using namespace std;
int main(){
int n;
cin>>n;
int ans,counter=0,a,temp=0,time=0;
while(temp<n){
cin>>a;
if(counter==0)
{
counter=1;
ans=a;
}
else if(counter>0){
if(ans==a)
++counter;
else
--counter;
}
++temp;
}
cout<<"The number "<<ans<<" is in the more majority ";
}
我的问题是 当你给 6 6 1 2 3 它说 3 占多数
我的问题在哪里? 谢谢
最佳答案
您正确地实现了算法,但没有正确解释它。
该算法假定存在多数元素(超过一半的元素是该特定元素)并返回它。如果假设为假,则必须遍历整个序列两次以检查是否真的存在多数。
在您的示例中没有多数,因此该算法不起作用。
关于c++ - 时间多数表决算法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19643492/