Kth largest element in a max-heap

后端 未结 4 747
清酒与你
清酒与你 2020-12-25 15:11

I\'m trying to come up with something to solve the following:

Given a max-heap represented as an array, return the kth largest element without modifyi

4条回答
  •  死守一世寂寞
    2020-12-25 16:02

    Max-heap in an array: element at i is larger than elements at 2*i+1 and 2*i+2 (i is 0-based)

    You'll need another max heap (insert, pop, empty) with element pairs (value, index) sorted by value. Pseudocode (without boundary checks):

    input: k
    1. insert (at(0), 0)
    2. (v, i) <- pop and k <- k - 1
    3. if k == 0 return v
    4. insert (at(2*i+1), 2*i+1) and insert (at(2*+2), 2*+2)
    5. goto 2
    

    Runtime evaluation

    • array access at(i): O(1)
    • insertion into heap: O(log n)
    • insert at 4. takes at most log(k) since the size of heap of pairs is at most k + 1
    • statement 3. is reached at most k times
    • total runtime: O(k log k)

提交回复
热议问题