leetcode--合并K个排序链表

合并 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站建设、成都网站设计、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的长兴网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

示例:

输入:[
  1->4->5,
  1->3->4,
  2->6
]输出: 1->1->2->3->4->4->5->6
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import heapq
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        h = []
        for node in lists:
            while node:
                h.append(node.val)
                node = node.next
        if not h:
            return None
        heapq.heapify(h) #转换成最小堆
        # 构造链表
        root = ListNode(heapq.heappop(h))
        curnode = root
        while h:
            nextnode = ListNode(heapq.heappop(h))
            curnode.next = nextnode
            curnode = nextnode
        return root

执行用时 : 104 ms, 在Merge k Sorted Lists的Python3提交中击败了77.24% 的用户

内存消耗 : 17.2 MB, 在Merge k Sorted Lists的Python3提交中击败了42.33% 的用户


新闻名称:leetcode--合并K个排序链表
浏览路径:http://myzitong.com/article/pijdjp.html