笔者在刷Leetcode时,23 merge k sorted lists 合并多个链表时用到了最小堆,借此总结下堆相关知识。
堆的结构其实就是完全二叉树,分为最大堆和最小堆。
最小堆就是根节点是最小的节点,然后左右子节点又是各自子节点中最小的(左右兄弟节点的大小则没有限制),依次类推。最大堆相反。


如上图所示,最小堆我们可以用数组来表示 [1,2,3,17,19,36,7,25,100],此时这种方式实现的堆叫做二叉堆。
关于二叉堆的操作有以下三种:
- make_heap
建堆,将一组数据建成最大堆或者最小堆,如上面数组所示的结构。
- push_heap
新元素进堆,也就是往数组中最末尾增加元素。
此时需要将新元素与堆中其他元素进行比较,找到合适的位置,自下而上的递归的进行 shiftUp 操作,使元素满足堆的性质。
- pop_heap
将数组末尾元素放到堆顶,删除末尾元素,达到了将堆顶元素删除的效果。
此时需要自上而下的递归的进行 shiftDown 操作,使元素满足堆的性质。
上面三个方法是C++提供给我们快速建堆和操作堆的三个方法。
实现
所以对于一个二叉堆来说最重要的就是实现上述的 shiftUp 和 shiftDown 操作,使操作堆后使堆中元素依然保持堆的性质。
对于二叉堆来说,数组中索引为 i 的元素,其左孩子元素索引为 2*i + 1, 右孩子元素索引为 2*i + 2, 父亲元素索引为 (i-1)/2。
下面是笔者自己实现的一个最小二叉堆:
class Heap {
public:
vector<int> heap;
int n;
int count;
Heap(vector<int>& arr) {
n = (int)arr.size();
count = n;
heap = arr;
buildHeap(arr);
}
void buildHeap(vector<int>& arr) {
for (int i = count/2-1; i >=0; --i) {
shift_down(i);
}
}
void push(int element) {
if (count >= n) {
return;
}
++count;
heap[count] = element;
shift_up(count);
}
int top() { return heap[0]; }
void pop() {
if (count == 0) {
return;
}
heap[0] = heap[count-1];
heap.pop_back();
--count;
shift_down(0);
}
private:
int left_child_idx(int pos) {
int idx = pos*2+1;
return idx >= n ? -1 : idx;
}
int right_child_idx(int pos) {
int idx = pos*2+2;
return idx >= n ? -1 : idx;
}
int parent_idx(int pos) {
return (pos-1) / 2;
}
void shift_up(int pos) {
if (pos == 0) { return; }
int p = parent_idx(pos);
if (heap[pos] < heap[p]) {
swap(heap[pos], heap[p]);
shift_up(p);
}
}
void shift_down(int pos) {
int l = left_child_idx(pos);
int r = right_child_idx(pos);
if (l == -1 && r == -1) {
return;
} else if (l == -1) {
return;
} else if (r == -1) {
if (heap[pos] > heap[l]) {
swap(heap[pos], heap[l]);
shift_down(l);
}
} else {
int idx = heap[l] < heap[r] ? l : r;
if (heap[pos] > heap[idx]) {
swap(heap[pos], heap[idx]);
shift_down(idx);
}
}
}
};因为堆是完全二叉树的缘故,当数组size 为 n, 有 n/2 的元素为叶子节点,所以buildHeap 时只需要从 n/2-1 处开始进行 shiftDown 调整即可。
C++ 建堆方法
C++ 里面提供了快速建堆的方法,就是之前笔者写的那三个方法。
static bool compare(int num1, int num2) {
return num1 > num2;
}
vector<int> list = {9, 6, 2, 4, 7, 0, 1, 8, 3, 5};
// 建堆
make_heap(list.begin(), list.end(), compare);
// 堆中添加元素
list.push_back(newNumber)
push_heap(list.begin(), list.end(), compare);
// 删除堆顶元素
pop_heap(list.begin(), list.end(), compare);
list.pop_back();priority_queue
priority_queue 所谓优先队列,这种类型的队列并不是先进先出,而是类似堆,每次先出现最大的(最大堆)或者最小的(最小堆)。
template <class T, class Container = vector<T>,class Compare = less<typename Container::value_type> > class priority_queue;默认优先队列是最大堆的形式,如果要最小堆则需要指定第三个比较参数。所以在遇到堆相关的,可以选择使用优先队列。
priority_queue<int, vector<int>, less<int>> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
heap.push(); // 等于入堆操作,保持堆性质
heap.top(); // 等于取堆顶元素
heap.pop(); // 等于出堆操作,保持堆性质