mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-13 20:20:58 +00:00
refactor: Replace 结点 with 节点 (#452)
* Replace 结点 with 节点 Update the footnotes in the figures * Update mindmap * Reduce the size of the mindmap.png
This commit is contained in:
@@ -14,23 +14,23 @@ class MaxHeap {
|
||||
init(nums: [Int]) {
|
||||
// 将列表元素原封不动添加进堆
|
||||
maxHeap = nums
|
||||
// 堆化除叶结点以外的其他所有结点
|
||||
// 堆化除叶节点以外的其他所有节点
|
||||
for i in stride(from: parent(i: size() - 1), through: 0, by: -1) {
|
||||
siftDown(i: i)
|
||||
}
|
||||
}
|
||||
|
||||
/* 获取左子结点索引 */
|
||||
/* 获取左子节点索引 */
|
||||
private func left(i: Int) -> Int {
|
||||
2 * i + 1
|
||||
}
|
||||
|
||||
/* 获取右子结点索引 */
|
||||
/* 获取右子节点索引 */
|
||||
private func right(i: Int) -> Int {
|
||||
2 * i + 2
|
||||
}
|
||||
|
||||
/* 获取父结点索引 */
|
||||
/* 获取父节点索引 */
|
||||
private func parent(i: Int) -> Int {
|
||||
(i - 1) / 2 // 向下整除
|
||||
}
|
||||
@@ -57,23 +57,23 @@ class MaxHeap {
|
||||
|
||||
/* 元素入堆 */
|
||||
func push(val: Int) {
|
||||
// 添加结点
|
||||
// 添加节点
|
||||
maxHeap.append(val)
|
||||
// 从底至顶堆化
|
||||
siftUp(i: size() - 1)
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从底至顶堆化 */
|
||||
/* 从节点 i 开始,从底至顶堆化 */
|
||||
private func siftUp(i: Int) {
|
||||
var i = i
|
||||
while true {
|
||||
// 获取结点 i 的父结点
|
||||
// 获取节点 i 的父节点
|
||||
let p = parent(i: i)
|
||||
// 当“越过根结点”或“结点无需修复”时,结束堆化
|
||||
// 当“越过根节点”或“节点无需修复”时,结束堆化
|
||||
if p < 0 || maxHeap[i] <= maxHeap[p] {
|
||||
break
|
||||
}
|
||||
// 交换两结点
|
||||
// 交换两节点
|
||||
swap(i: i, j: p)
|
||||
// 循环向上堆化
|
||||
i = p
|
||||
@@ -86,9 +86,9 @@ class MaxHeap {
|
||||
if isEmpty() {
|
||||
fatalError("堆为空")
|
||||
}
|
||||
// 交换根结点与最右叶结点(即交换首元素与尾元素)
|
||||
// 交换根节点与最右叶节点(即交换首元素与尾元素)
|
||||
swap(i: 0, j: size() - 1)
|
||||
// 删除结点
|
||||
// 删除节点
|
||||
let val = maxHeap.remove(at: size() - 1)
|
||||
// 从顶至底堆化
|
||||
siftDown(i: 0)
|
||||
@@ -96,11 +96,11 @@ class MaxHeap {
|
||||
return val
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从顶至底堆化 */
|
||||
/* 从节点 i 开始,从顶至底堆化 */
|
||||
private func siftDown(i: Int) {
|
||||
var i = i
|
||||
while true {
|
||||
// 判断结点 i, l, r 中值最大的结点,记为 ma
|
||||
// 判断节点 i, l, r 中值最大的节点,记为 ma
|
||||
let l = left(i: i)
|
||||
let r = right(i: i)
|
||||
var ma = i
|
||||
@@ -110,11 +110,11 @@ class MaxHeap {
|
||||
if r < size(), maxHeap[r] > maxHeap[ma] {
|
||||
ma = r
|
||||
}
|
||||
// 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
|
||||
// 若节点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
|
||||
if ma == i {
|
||||
break
|
||||
}
|
||||
// 交换两结点
|
||||
// 交换两节点
|
||||
swap(i: i, j: ma)
|
||||
// 循环向下堆化
|
||||
i = ma
|
||||
|
||||
Reference in New Issue
Block a user