C++实现小根堆
首先,我们需要了解什么是堆(heap)。堆是一种数据结构,它可以在O(log n)的时间复杂度内完成插入、删除最大/最小值的操作。堆又可以分为大根堆和小根堆两种类型,大根堆是指堆顶元素最大,而小根堆是指堆顶元素最小。
在C++中,我们可以用STL中的priority_queue来实现堆。但是如果我们想要更深入地理解堆以及手动实现堆的话,就需要自己动手写一个小根堆了。
下面是一个基于数组实现的小根堆的C++代码:
#include <iostream>
#include <vector>
using namespace std;
class MinHeap{
private:
vector<int> heap;
void percolateUp(int index){
while(index > 0){
int parentIndex = (index - 1) / 2;
if(heap[parentIndex] > heap[index]){
swap(heap[parentIndex], heap[index]);
index = parentIndex;
}
else{
break;
}
}
}
void percolateDown(int index){
while(index < heap.size()){
本文介绍了C++如何实现小根堆,包括堆的数据结构概念、大根堆与小根堆的区别,以及如何使用vector实现小根堆的基本操作:insert、extractMin和isEmpty。代码示例展示了如何保持堆的性质并进行元素的增删。
订阅专栏 解锁全文
385

被折叠的 条评论
为什么被折叠?



