【发布时间】:2021-08-01 16:25:39
【问题描述】:
我们了解到,从头开始构建最小或最大堆的时间复杂度需要 O(n) 时间。
但由于 STL 中的 priority_queue 需要 O(log n) 时间进行插入,
所以使用 priority_queue 从头开始创建堆需要O(n*log n) 时间。不是吗?
使用向量也是如此。
有没有其他方法可以使用 STL 中的任何内置函数在 O(n) 时间创建堆?
【问题讨论】:
我们了解到,从头开始构建最小或最大堆的时间复杂度需要 O(n) 时间。
但由于 STL 中的 priority_queue 需要 O(log n) 时间进行插入,
所以使用 priority_queue 从头开始创建堆需要O(n*log n) 时间。不是吗?
使用向量也是如此。
有没有其他方法可以使用 STL 中的任何内置函数在 O(n) 时间创建堆?
【问题讨论】:
std::priority_queue 的构造函数all have O(N) complexity1,其中 N 是您传递的元素数。
例如
explicit priority_queue( const Compare& compare = Compare(), const Container& cont = Container() );(3)
- 复制构造底层容器
c,其内容为cont。复制构造比较函子comp,其内容为compare。致电std::make_heap(c.begin(), c.end(), comp)。
复杂性
- O(N) 次比较,其中 N 为
cont.size()。此外,O(N) 调用value_type的构造函数,其中N是cont.size()。
【讨论】: