c++ - 时间多数表决算法错误

标签 c++ algorithm

这是算法 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/

相关文章:

c++ - 比特集比 bool 数组快吗?

python - 双循环的迭代计数器

algorithm - 面试题: Buy and sell stocks to maximize profit with constraint of not buying once you sell

java - 如何反转这个从第 n 个元素到最后的链表

c# - 算法求助!与伙伴一起搜索字符串的快速算法

c++ - 如何找到像参数一样传递的一些数字的最大序列?

c++ - 将 std::string 转换为 vector<char>

c++ - 通过 system() 调用启动另一个程序会阻塞套接字

c++ - 当对象包含另一个对象的 Vector 时无法设置值

algorithm - 两个序列和具有相同模块的最小步骤