【问题标题】:Why is the complexity of heap Delete element equal to O(logn) and Build is O(n)?为什么堆Delete element的复杂度等于O(logn)而Build是O(n)?
【发布时间】:2023-04-01 06:03:01
【问题描述】:

我在理解复杂性方面遇到了困难,您能否解释一下为什么堆中的删除复杂性等于 O(log n) 以及为什么构建是 O(n)? (我假设插入复杂度 O(1) 仅指添加元素,没有位置切换)。 我们在底部添加的元素不是假设在最坏的情况下一直向上移动吗?因此(即使我不明白为什么它是 log n ),Build 也不应该是 O(log n) 吗?

【问题讨论】:

  • 想想找到合适的地方,根据结构复制所有元素 vs 清理并向上移动元素
  • @gkhaos 建筑物不是在做同样的事情吗?在最坏的情况下将元素一直向上移动,因此在一个分支上向上移动?如果有意义的话。
  • 也许你可以参考你发现堆构建比删除慢的来源。在简短的谷歌搜索中,我发现了这个问题:Why deallocating heap memory is much slower than allocating it?

标签: heap complexity-theory analysis


【解决方案1】:

从一个数组构造一个堆是 O(n),因为它使用build_heap 算法来重新排列数组。这与在最坏的情况下进行 O(log n) 的 n 插入操作根本不同。通过重复插入构建堆是 O(n log n)。

删除最高优先级的项目使用此算法:

move the last item in the heap to the root
decrease the count by 1
starting at the new root node, move it down the heap to its proper place:
while the node is larger than either of its children
    swap the node with its smallest child

这是 O(log n),因为将节点向下移动到堆中可能需要 O(log n) 交换。

有关build_heap 算法的说明,请参阅how to build heap tree?

请参阅 https://stackoverflow.com/a/49781979/56778 以了解 build_heap 是 O(n) 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-23
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多