线性时间表决算法。我不明白这一点我不、这一点、线性、算法

2023-09-10 23:27:31 作者:早安晚安祝你入土为安、

当我在读这(找到最常见的入门在一个阵列),该博耶和摩尔的线性时间表决算法建议。

As I was reading this (Find the most common entry in an array), the Boyer and Moore's Linear Time Voting Algorithm was suggested.

如果您按照链接到的网站,有一个循序渐进的算法如何工作一步的解释。对于给定的顺序, AAACCBBCCCBCC 其presents合适的解决方案。

If you follow the link to the site, there is a step by step explanation of how the algorithm works. For the given sequence, AAACCBBCCCBCC it presents the right solution.

当我们向前移动指针超过   元素e:

When we move the pointer forward over an element e:   如果计数器为0,我们设置当前考生E和我们设定的   计数器为1。   如果计数器不为0,我们递增或递减计数器   根据步骤e是否为当前   候选人。    If the counter is 0, we set the current candidate to e and we set the counter to 1. If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.

当我们完成,目前   候选是大多数元件,如果   还有一大部分。

When we are done, the current candidate is the majority element, if there is a majority.

如果我用这个算法在一张纸 AAACCBB 作为输入,建议的候选人将成为乙什么显然是错误的。

If I use this algorithm on a piece of paper with AAACCBB as input, the suggested candidate would become B what is obviously wrong.

在我看来,有两种可能性

As I see it, there are two possibilities

的作者从来没有尝试过他们的算法对其他任何东西比 AAACCBBCCCBCC ,是完全不称职的,应当当场被解雇的(doubtfull)的。 我清楚地失去了一些东西,必须得到禁止#1和绝对不允许再触碰任何涉及逻辑。 The authors have never tried their algorithm on anything else than AAACCBBCCCBCC, are completely incompetent and should be fired on the spot (doubtfull). I am clearly missing something, must get banned from Stackoverflow and never be allowed again to touch anything involving logic.

请注意:这里是AA C ++实现的算法从NIEK桑德斯。我相信他正确地实现这个想法,因此它有同样的问题(或不是吗?)。

Note: Here is a a C++ implementation of the algorithm from Niek Sanders. I believe he correctly implemented the idea and as such it has the same problem (or doesn't it?).

推荐答案

该算法只能当设定具有多数 - 半数以上为相同的元素。 AAACCBB 在你的例子中有没有这样的多数。最常见的字母出现3次,字符串长度为7。

The algorithm only works when the set has a majority -- more than half of the elements being the same. AAACCBB in your example has no such majority. The most frequent letter occurs 3 times, the string length is 7.