Determining if an array has a k-majority element

后端 未结 3 900
天涯浪人
天涯浪人 2021-01-02 08:47

Suppose that, given an n-element multiset A (not sorted), we want an O(n) time algorithm for determining whether A contains a majority element, i.e., an element that occurs

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 09:19

    I don't know if you've seen this one, but it may help to give you ideas:

    Suppose you know there is a majority element in an array L.

    One way to find the element is as follows:

    Def FindMajorityElement(L):
    
        Count = 0
    
        Foreach X in L
    
            If Count == 0
                Y = X
    
            If X == Y
                Count = Count + 1
            Else
                Count = Count - 1
    
        Return Y
    

    O(n) time, O(1) space

提交回复
热议问题