首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Min堆提取2个最小元素

Min堆提取2个最小元素
EN

Stack Overflow用户
提问于 2016-12-15 07:21:46
回答 1查看 522关注 0票数 0

我有一个最低限度的堆。

代码语言:javascript
复制
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)时间内获得堆中的两个最小值,例如只使用一个循环?

致以问候。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-15 07:36:59

一旦堆形成,您就可以在O(logn)时间完成它。您可以通过一个pop和两个查询来完成它。

代码语言:javascript
复制
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

看看这个会有帮助的:queue

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41158536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档