Python 中合并 K 排序列表的程序
pythonserver side programmingprogramming更新于 2026/2/1 18:20:17
假设我们有一些列表,这些列表是排序的。我们必须将这些列表合并为一个列表。为了解决这个问题,我们将使用堆数据结构。因此,如果列表为 [1,4,5]、[1,3,4]、[2,6],则最终列表将为 [1,1,2,3,4,4,5,6]。
为了解决这个问题,我们将遵循以下步骤 −
- n := 列表大小
- 堆 := 一个新列表
- 对于每个索引 i 和列表 [i] 的行,执行
- 如果行非空,则
- 将 (row[0], i, 0) 插入堆
- 如果行非空,则
- res := 一个新列表
- 当堆不为空时,执行
- num、row、col := 堆的顶部元素
- 插入res 末尾的数字
- 如果 col < 列表的大小[row] - 1,则
- 将列表[row, col + 1]、row、col + 1 插入到堆中
- 返回 res
让我们看看下面的实现以便更好地理解 −
示例
import heapq class Solution: def solve(self, lists): n = len(lists) heap = [] for i, row in enumerate(lists): if row: heapq.heappush(heap, (row[0], i, 0)) res = [] while heap: num, row, col = heapq.heappop(heap) res.append(num) if col < len(lists[row]) - 1: heapq.heappush(heap, (lists[row][col + 1], row, col + 1)) return res ob = Solution() lists = [[],[],[11, 13],[],[4, 4, 14],[4],[11],[1, 8]] print(ob.solve(lists))
输入
[[],[],[11, 13],[],[4, 4, 14],[4],[11],[1, 8]]
输出
[1, 4, 4, 4, 8, 11, 11, 13, 14]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

