如果底层数据结构是list,heapq的push操作怎么会是O(log n)时间呢?

How can heapq's push operation be O(log n) time if the underlying data structure is a list?

列表不是需要 O(n) 时间来增加它的大小吗?那么,heap.heappush 怎么可能是 O(log n)?

A list 摊销 O(1) 追加;每隔一段时间,它需要扩展底层容量,但通常 append 只需要声明已分配的容量。

所以是的,每隔一段时间,heapq.heappush 会导致 O(n) 重新分配基础 list 的存储,但绝大多数时候,添加额外项(通过 append 内部完成)是 O(1),然后是 O(log n) 筛选操作以将其移动到堆中的正确位置(重新建立堆不变量);筛选操作是通过元素交换实现的,它们都是 O(1),而不是插入和删除(每个都是 O(n)