2016-12-15 45 views
0

我有一個最小堆即viz。Min Heap Extract 2最小元素

priority_queue<double, vector<double>, greater<double>> min_heap; 
// push vector values to heap 
for (const auto& e : rand) 
    min_heap.push(e); 

如何,我可以得到O(n)時間內這堆2個最小值,只用一個循環說呢?

問候。

+0

你知道如何使用priority_queue?你知道各種方法和各種複雜性嗎? –

+0

@MooingDuck沒有那麼誠實。從來沒有明確地使用它們,現在看來我需要學習。 –

回答

3

一旦你的堆形成,你可以在O(logn)時間內完成。你可以用一個pop和2個查詢來完成。在此

int min1 = min_heap.top(); //get the minimum element 
min_heap.pop(); //pop the minimum element from the heap 
int min2 = min_heap.top(); //get the second minimum element(the new top) 
min_heap.push(min1); //push the old 'top' to restore the heap to its old state 

展望會幫助:http://en.cppreference.com/w/cpp/container/priority_queue

相關問題