Kth largest element in a max-heap

后端 未结 4 742
清酒与你
清酒与你 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

    No, there's no O(log n)-time algorithm, by a simple cell probe lower bound. Suppose that k is a power of two (without loss of generality) and that the heap looks like (min-heap incoming because it's easier to label, but there's no real difference)

          1
       2     3
      4 5   6 7
    .............
    permutation of [k, 2k).
    

    In the worst case, we have to read the entire permutation, because there are no order relations imposed by the heap, and as long as k is not found, it could be in any location not yet examined. This takes time Omega(k), matching the (complicated!) algorithm posted by templatetypedef.

提交回复
热议问题