Print the biggest K elements in a given heap in O(K*log(K))?

前端 未结 5 2012
粉色の甜心
粉色の甜心 2020-12-03 01:56

Given the following problem , I\'m not completely sure with my current solution :

Question :

Given a maximum heap with n ele

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 02:20

    It is a simple and elegant algorithm to get first k elements of a max heap in k log(k) time.
    
    steps:-
    
    1.construct another max heap name it auxiliary heap
    2.add root element of main heap to auxiliary heap
    3.pop out the element from auxiliary heap and add it's 2 children to the heap
    4.do step 2 and 3 till k elements have been popped out from auxiliary heap. Add the popped element's children to the auxiliary heap.
    

提交回复
热议问题