Linear time majority algorithm?

前端 未结 7 1370
深忆病人
深忆病人 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

    If you know that the majority element is in more of half of the array size then there is such algorithm. You keep track of the most common element and the repetitions of it. When you start that element is the first and there is one repetition. If the next element is different from the current most common then you substract one from the repetitions. If the repetitions become zero then you change the most common with the element you are currently observing and set the repetitions to 1.

提交回复
热议问题