mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-27 12:01:49 +08:00
Fix Repo
This commit is contained in:
@@ -445,10 +445,7 @@ comments: true
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
/* 访问堆顶元素 */
|
||||
int peek() {
|
||||
return maxHeap[0];
|
||||
}
|
||||
[class]{MaxHeap}-[func]{peek}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
@@ -548,28 +545,9 @@ comments: true
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
/* 元素入堆 */
|
||||
void push(int val) {
|
||||
// 添加结点
|
||||
maxHeap.push_back(val);
|
||||
// 从底至顶堆化
|
||||
shifUp(size() - 1);
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从底至顶堆化 */
|
||||
void shifUp(int i) {
|
||||
while (true) {
|
||||
// 获取结点 i 的父结点
|
||||
int p = parent(i);
|
||||
// 当“越过根结点”或“结点无需修复”时,结束堆化
|
||||
if (p < 0 || maxHeap[i] <= maxHeap[p])
|
||||
break;
|
||||
// 交换两结点
|
||||
swap(maxHeap[i], maxHeap[p]);
|
||||
// 循环向上堆化
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
[class]{MaxHeap}-[func]{push}
|
||||
|
||||
[class]{MaxHeap}-[func]{siftUp}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
@@ -758,39 +736,9 @@ comments: true
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
/* 从结点 i 开始,从顶至底堆化 */
|
||||
void shifDown(int i) {
|
||||
while (true) {
|
||||
// 判断结点 i, l, r 中值最大的结点,记为 ma
|
||||
int l = left(i), r = right(i), ma = i;
|
||||
// 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
|
||||
if (l < size() && maxHeap[l] > maxHeap[ma])
|
||||
ma = l;
|
||||
if (r < size() && maxHeap[r] > maxHeap[ma])
|
||||
ma = r;
|
||||
// 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
|
||||
if (ma == i)
|
||||
break;
|
||||
swap(maxHeap[i], maxHeap[ma]);
|
||||
// 循环向下堆化
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* 元素出堆 */
|
||||
void poll() {
|
||||
// 判空处理
|
||||
if (empty()) {
|
||||
cout << "Error:堆为空" << endl;
|
||||
return;
|
||||
}
|
||||
// 交换根结点与最右叶结点(即交换首元素与尾元素)
|
||||
swap(maxHeap[0], maxHeap[size() - 1]);
|
||||
// 删除结点
|
||||
maxHeap.pop_back();
|
||||
// 从顶至底堆化
|
||||
shifDown(0);
|
||||
}
|
||||
[class]{MaxHeap}-[func]{poll}
|
||||
|
||||
[class]{MaxHeap}-[func]{siftDown}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
@@ -993,15 +941,7 @@ comments: true
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
/* 构造函数,根据输入列表建堆 */
|
||||
MaxHeap(vector<int> nums) {
|
||||
// 将列表元素原封不动添加进堆
|
||||
maxHeap = nums;
|
||||
// 堆化除叶结点以外的其他所有结点
|
||||
for (int i = parent(size() - 1); i >= 0; i--) {
|
||||
shifDown(i);
|
||||
}
|
||||
}
|
||||
[class]{MaxHeap}-[func]{MaxHeap}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
Reference in New Issue
Block a user