This commit is contained in:
krahets
2023-04-09 05:12:22 +08:00
parent 01d05cc1f0
commit 37f11aff68
27 changed files with 265 additions and 248 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ comments: true
```python title="my_heap.py"
def __init__(self, nums: list[int]):
""" 构造方法 """
"""构造方法"""
# 将列表元素原封不动添加进堆
self.max_heap = nums
# 堆化除叶节点以外的其他所有节点
+8 -8
View File
@@ -366,15 +366,15 @@ comments: true
```python title="my_heap.py"
def left(self, i: int) -> int:
""" 获取左子节点索引 """
"""获取左子节点索引"""
return 2 * i + 1
def right(self, i: int) -> int:
""" 获取右子节点索引 """
"""获取右子节点索引"""
return 2 * i + 2
def parent(self, i: int) -> int:
""" 获取父节点索引 """
"""获取父节点索引"""
return (i - 1) // 2 # 向下整除
```
@@ -533,7 +533,7 @@ comments: true
```python title="my_heap.py"
def peek(self) -> int:
""" 访问堆顶元素 """
"""访问堆顶元素"""
return self.max_heap[0]
```
@@ -682,14 +682,14 @@ comments: true
```python title="my_heap.py"
def push(self, val: int):
""" 元素入堆 """
"""元素入堆"""
# 添加节点
self.max_heap.append(val)
# 从底至顶堆化
self.sift_up(self.size() - 1)
def sift_up(self, i: int):
""" 从节点 i 开始,从底至顶堆化 """
"""从节点 i 开始,从底至顶堆化"""
while True:
# 获取节点 i 的父节点
p = self.parent(i)
@@ -996,7 +996,7 @@ comments: true
```python title="my_heap.py"
def pop(self) -> int:
""" 元素出堆 """
"""元素出堆"""
# 判空处理
assert not self.is_empty()
# 交换根节点与最右叶节点(即交换首元素与尾元素)
@@ -1009,7 +1009,7 @@ comments: true
return val
def sift_down(self, i: int):
""" 从节点 i 开始,从顶至底堆化 """
"""从节点 i 开始,从顶至底堆化"""
while True:
# 判断节点 i, l, r 中值最大的节点,记为 ma
l, r, ma = self.left(i), self.right(i), i