Linear time majority algorithm?

前端 未结 7 1374
深忆病人
深忆病人 2020-12-05 01:03

Can anyone think of a linear time algorithm for determining a majority element in a list of elements? The algorithm should use O(1) space.

If n is the s

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 01:42

    I think it is possible, using Boyer-Moore, though not directly.

    As Matthew stated, Boyer-Moore only guarantees to find the majority element for a slightly different definition of majority, called strict majority. Your definition is slightly weaker, but not by much.

    1. Execute Boyer-Moore: O(N) time, O(1) space
    2. Check that the candidate fulfills the condition: O(N) time, O(1) space
    3. If it doesn't, execute Boyer-Moore, but ignores the instances of the "failed" candidate: O(N) time, O(1) space
    4. Check that the (new) candidate fulfills the condition: O(N) time, O(1) space

    The 1. and 2. steps are straight-forward. The 3. works because by removing instances of the failed candidates, we are now looking for a strict majority element. The 4. is optional, and only to be used if there is a possibility that no majority element exists.

提交回复
热议问题