algorithm - 线性时间投票算法。我不明白

标签 algorithm language-agnostic puzzle

当我阅读这篇文章(Find the most common entry in an array)时,Boyer and Moore's Linear Time Voting Algorithm有人建议。

如果您点击该站点的链接,将逐步解释该算法的工作原理。对于给定的序列,AAACCBBCCCBCC 它给出了正确的解决方案。

When we move the pointer forward over an element 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 作为输入,建议的候选将变为 B,这显然是错误的。

在我看来,有两种可能

  1. 作者从未在 AAACCBBCCCBCC 以外的任何地方尝试过他们的算法,完全无能,应该当场解雇(怀疑)
  2. 我显然遗漏了一些东西,必须被禁止使用 Stackoverflow,并且再也不允许接触任何涉及逻辑的东西。

注意:这是一个C++ implementation of the algorithm来自尼克·桑德斯。我相信他正确地实现了这个想法,因此它有同样的问题(或者没有?)。

最佳答案

该算法仅在集合占多数时才有效——超过一半的元素相同。 AAACCBB 在你的例子中没有这样的多数。出现次数最多的字母出现3次,字符串长度为7。

关于algorithm - 线性时间投票算法。我不明白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/780937/

相关文章:

ruby - 用另一个字符替换 Ruby 中的字符

algorithm - 如何在不使用 "/"和 "%"的情况下有效地获得商和余数?

algorithm - 找到提供最佳压缩的前缀子串

java - 8 拼图的第二次迭代不起作用

language-agnostic - 删除目录中每个文件的算法,给定列表中的某些文件除外

python - 计算两个 D30 的复杂抛出的精确结果

algorithm - 计算数字集的均匀性或差异性的快速方法

c++ - map 和 vector 上的 std::set_difference 会引发转换错误

arrays - 如何在功能上而不是程序上在线性时间内 "invert"数组?

database - 有谁知道一个很好的图书馆可以将一个人的名字映射到他或她的性别?