Skip to content

Commit 19d2ec2

Browse files
committed
heapsort use heapq; add heap leetcode merge-k-sorted-lists
1 parent d872fea commit 19d2ec2

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

docs/15_堆与堆排序/heap_and_heapsort.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def test_heapsort_reverse():
122122
```
123123

124124
# python 里的 heapq
125-
python 其实自带了 heapq 模块,用来实现堆的相关操作,原理是类似的。请你阅读相关文档
125+
python 其实自带了 heapq 模块,用来实现堆的相关操作,原理是类似的。请你阅读相关文档并使用内置的 heapq 模块完成堆排序
126126

127127
# 练习题
128128

@@ -136,3 +136,7 @@ python 其实自带了 heapq 模块,用来实现堆的相关操作,原理是
136136
- 《算法导论》第 6 章 Heapsort
137137
- 《Data Structures and Algorithms in Python》 13.5 节 Heapsort
138138
- 阅读 Python heapq 模块的文档
139+
140+
# Leetcode
141+
142+
合并 k 个有序链表 https://leetcode.com/problems/merge-k-sorted-lists/description/

docs/15_堆与堆排序/heap_and_heapsort.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,18 @@ def test_heapsort_reverse():
123123
l = list(range(10))
124124
random.shuffle(l)
125125
assert heapsort_reverse(l) == sorted(l, reverse=True)
126+
127+
128+
def heapsort_use_heapq(iterable):
129+
from heapq import heappush, heappop
130+
items = []
131+
for value in iterable:
132+
heappush(items, value)
133+
return [heappop(items) for i in range(len(items))]
134+
135+
136+
def test_heapsort_use_heapq():
137+
import random
138+
l = list(range(10))
139+
random.shuffle(l)
140+
assert heapsort_use_heapq(l) == sorted(l)

0 commit comments

Comments
 (0)