簡體   English   中英

在 C++ STL 中使用 priority_queue 和 vector 創建堆的時間復雜度是多少?

[英]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)

  1. 使用cont的內容復制構造底層容器c 使用compare的內容復制構造比較函子comp 調用std::make_heap(c.begin(), c.end(), comp)

復雜

  1. O(N) 比較,其中 N 是cont.size() 此外, O(N) 調用value_type的構造函數,其中 N 是cont.size()
  1. 除了移動構造函數,它會在恆定時間內竊取它的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM