合并k个有序列表-python

主要思路:借鉴堆、队列特点,构建新的有序结果

复制代码
# merge the k sorted list
# main idea: 将每个list放入队列,初始一个小顶堆,size为list个数,value为队列的首个元素,交替寻找最小值存储到新list中
import heapq
from collections import deque
nums = [[1,3,43], [16,29,89], [4, 33, 88, 100,1011]]
# 队列化
queues = list(map(deque, nums))
heap = []
for i, q in enumerate(queues):
    heap.append((q.popleft(), i))
# 堆化,弹出最小值:
heapq.heapify(heap)
result = []
while heap:
    # 弹出最小元素
    val, index = heapq.heappop(heap)
    result.append(val)
    # 找出弹出元素所在队列中的下一个元素,push到堆中,重复以上步骤
    if queues[index]:
        new_num = queues[index].popleft()
        heapq.heappush(heap, (new_num, index))
result
复制代码

 

参考:https://izsk.me/2019/03/02/%E5%90%88%E5%B9%B6K%E4%B8%AA%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84(python)/

posted @   今夜无风  阅读(156)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示