[英]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)
- Copy-constructs the underlying container
c
with the contents ofcont
.使用
cont
的内容复制构造底层容器c
。 Copy-constructs the comparison functorcomp
with the contents ofcompare
.使用
compare
的内容复制构造比较函子comp
。 Callsstd::make_heap(c.begin(), c.end(), comp)
.调用
std::make_heap(c.begin(), c.end(), comp)
。
Complexity
复杂
- O(N) comparisons, where N is
cont.size()
.O(N) 比较,其中 N 是
cont.size()
。 Additionally, O(N) calls to the constructor ofvalue_type
, where N iscont.size()
.此外, O(N) 调用
value_type
的构造函数,其中 N 是cont.size()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.