leetcode--合并K个排序链表

发布时间:2020-03-31 16:21:15 作者:ading2016
来源:网络 阅读:367

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

示例:

输入:[
  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% 的用户


推荐阅读:
  1. leetcode--合并两个有序的链表
  2. 剑指offer:合并两个排序的链表

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 算法

上一篇:关于redis启动与连接的方法介绍

下一篇:三个半月建一座高等级数据中心

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》