且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多数表决算法 - 错了吗?

更新时间:2022-11-29 14:52:46

该算法是正确的:有一个在您的例子无多数元素。一个元素居多,只有当它是超过值的50%。

The algorithm is correct: there is no majority element in your examples. An element is in the majority only if it is more than 50% of the values.

如果您希望检测,其中最常见的元素的计数的情况下 N / 2 ,那么我看不出有什么办法做到这一点在一个通和 O(1)的空间。我***的尝试是:

If you wish to detect the case where the most frequent element has a count of N/2, then I don't see any way to do it in one pass and O(1) space. My best attempt is:

  • 运行相同的算法和以前一样,但请记住previous候选人为好。
  • 如果您在切换的最后一个元素,那么正确答案要么是你目前或previous候选人。
  • 运行另一张通行证,每个计数的数量,并进行比较。