【问题标题】:How to delete the minimum key in a max heap?如何删除最大堆中的最小键?
【发布时间】:2013-02-19 05:04:21
【问题描述】:

我需要实现一个函数 HEAP-DELETE-MIN(Array) 来删除最大堆中的最小整数。我不是要求函数本身,但有人可以为我提供一些 pseudocode 来帮助我入门吗?这将是一个很大的帮助。数组在函数结束时应保持最大堆。

【问题讨论】:

    标签: heap max-heap


    【解决方案1】:

    基本上你需要做的是搜索存储在数组中的隐式堆的所有叶节点。它将是堆的一个叶子节点,因为它的父节点必须大于它(最大堆属性),并且我们知道叶子是从索引 n/2 及以后存储的(尽管这不会损害我们的算法复杂性)。所以基本上你应该做的是:

    1) Search the array for the minimum element
    2) Place the last-inserted heap element in the position of the minimum element (essentially this is the delete)
    3) Upheap the replaced node to restore maximum heap property and correct storage of the heap in the array
    

    这将花费 O(n) 来搜索最小元素,然后 O(1) 用于切换,最后 O(log n) 用于上堆。总的来说,这是线性时间,基本上是你能做的最好的。

    记住要小心索引操作,2*i 是节点 i 的左孩子,2*i+1 是节点 i 在基于数组的堆中的右孩子(假设数组的第 0 个元素总是空且堆的根在索引 1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 2013-12-25
      • 2022-10-23
      • 2012-05-26
      • 2019-04-11
      • 2012-05-18
      • 1970-01-01
      相关资源
      最近更新 更多