最小堆提取物2最小元素
Min Heap Extract 2 Smallest Element
我有一个最小堆。
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
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 从控制台中删除最后打印的元素
- 最小堆提取物2最小元素