【问题标题】:What is the time complexity of creating a heap using priority_queue and vector in C++ STL?在 C++ STL 中使用 priority_queue 和 vector 创建堆的时间复杂度是多少?
【发布时间】:2021-08-01 16:25:39
【问题描述】:

我们了解到,从头开始构建最小或最大堆的时间复杂度需要 O(n) 时间。

但由于 STL 中的 priority_queue 需要 O(log n) 时间进行插入,

所以使用 priority_queue 从头开始​​创建堆需要O(n*log n) 时间。不是吗? 使用向量也是如此。 有没有其他方法可以使用 STL 中的任何内置函数在 O(n) 时间创建堆?

【问题讨论】:

    标签: c++ stl heap


    【解决方案1】:

    std::priority_queue 的构造函数all have O(N) complexity1,其中 N 是您传递的元素数。

    例如

    explicit priority_queue( const Compare& compare = Compare(), const Container& cont = Container() );(3)

    1. 复制构造底层容器c,其内容为 cont。复制构造比较函子comp,其内容为 compare。致电std::make_heap(c.begin(), c.end(), comp)

    复杂性

    1. O(N) 次比较,其中 N 为 cont.size()。此外,O(N) 调用value_type的构造函数,其中N是cont.size()
    1. 除了移动构造函数,它会在恒定时间内窃取它的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 2020-07-15
      • 2020-02-03
      • 2018-11-24
      • 2014-05-27
      相关资源
      最近更新 更多