Determining if an array has a k-majority element

后端 未结 3 901
天涯浪人
天涯浪人 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:22

    The method that you described just needs to be used recursively.

    Remembering that select moves the elements that are less or equal to the median to the left of the median.

    If A is of size n.

    Find the median of A. Now find the median of each of the two sub multi-sets of length n/2 that were partitioned by the median. Find the median of each of the four sub multi-sets of length n/4 that were partitioned by the medians. Continue recursively until the leaves are of length n/k. Now the height of the recursive tree is O(lgk). On each level of the recursive tree, there are O(n) operations. If there exist a value that is repeated at least n/k times then it will be in one of these k with length of n/k sub multi-sets. The last operations is also done in O(n). So you get the requested running time of O(nlgk).

提交回复
热议问题