最小堆提取物2最小元素

Min Heap Extract 2 Smallest Element

本文关键字:元素 提取物      更新时间:2023-10-16

我有一个最小堆。

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个最小值?

问候。

一旦形成堆,就可以在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