How do I find the median of numbers in linear time using heaps?

前端 未结 7 843
谎友^
谎友^ 2020-12-04 06:59

Wikipedia says:

Selection algorithms: Finding the min, max, both the min and max, median, or even the k-th largest element can be done i

7条回答
  •  有刺的猬
    2020-12-04 07:20

    if you know more about heap data structure, you will easily understand that that s actually the case. heap structure can be built in O(n) time, there is min heap and max heap. min heap root element will give you the smallest element. max heap root element will give you the max element. Just by building the heap you find the min and max. same idea for median and kth largest, while building your heap, you can find the median and kth largest by looking at left or right branch of the tree and by keeping a constant amount of memory to store the element number. etc.

提交回复
热议问题