简体   繁体   English

在 C++ STL 中使用 priority_queue 和 vector 创建堆的时间复杂度是多少?

[英]What is the time complexity of creating a heap using priority_queue and vector in C++ STL?

We have been taught that time complexity for building a min or max heap from scratch takes O(n) time.我们被告知,从头开始构建最小或最大堆的时间复杂度需要O(n)时间。

But since priority_queue in STL takes O(log n) time for insertion,但是由于 STL 中的 priority_queue 需要O(log n)时间进行插入,

So making heap from scratch using priority_queue would take O(n*log n) time.因此,使用priority_queue从头开始创建堆需要O(n*log n)时间。 isn't it?不是吗? and same goes for using vector also.使用向量也是如此。 Is there any other way in which I could use any built-in function from STL to create heap in O(n) time?有没有其他方法可以使用 STL 中的任何内置 function 在O(n)时间内创建堆?

std::priority_queue 's constructors all have O(N) complexity 1 , where N is the number of elements you pass. std::priority_queue的构造函数都具有 O(N) 复杂度1 ,其中 N 是您传递的元素数。

Eg例如

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

  1. Copy-constructs the underlying container c with the contents of cont .使用cont的内容复制构造底层容器c Copy-constructs the comparison functor comp with the contents of compare .使用compare的内容复制构造比较函子comp Calls std::make_heap(c.begin(), c.end(), comp) .调用std::make_heap(c.begin(), c.end(), comp)

Complexity复杂

  1. O(N) comparisons, where N is cont.size() . O(N) 比较,其中 N 是cont.size() Additionally, O(N) calls to the constructor of value_type , where N is cont.size() .此外, O(N) 调用value_type的构造函数,其中 N 是cont.size()
  1. Besides the move constructor, which steals it's argument in constant time.除了移动构造函数,它会在恒定时间内窃取它的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM