[英]What is the time complexity of creating a heap using priority_queue and vector in C++ STL?
我們被告知,從頭開始構建最小或最大堆的時間復雜度需要O(n)
時間。
但是由於 STL 中的 priority_queue 需要O(log n)
時間進行插入,
因此,使用priority_queue從頭開始創建堆需要O(n*log n)
時間。 不是嗎? 使用向量也是如此。 有沒有其他方法可以使用 STL 中的任何內置 function 在O(n)
時間內創建堆?
std::priority_queue
的構造函數都具有 O(N) 復雜度1 ,其中 N 是您傳遞的元素數。
例如
explicit priority_queue( const Compare& compare = Compare(), const Container& cont = Container() );
(3)
- 使用
cont
的內容復制構造底層容器c
。 使用compare
的內容復制構造比較函子comp
。 調用std::make_heap(c.begin(), c.end(), comp)
。
復雜
- O(N) 比較,其中 N 是
cont.size()
。 此外, O(N) 調用value_type
的構造函數,其中 N 是cont.size()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.