题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param lists ListNode类一维数组 
# @return ListNode类
#
class Solution:
    def mergeKLists(self , lists: List[ListNode]) -> ListNode:
        # write code here
        if not lists:
            return 
		# 导入堆
        import heapq
        heap = []
        for sub_list in lists:
            while sub_list:
                heapq.heappush(heap,sub_list.val)
                sub_list = sub_list.next
        
		dummy = ListNode(0)
        head = dummy
        while heap:
            head.next = ListNode(heapq.heappop(heap))
            head = head.next
        return dummy.next

全部评论

相关推荐

努力成为C语言高手:质疑大祥老师,理解大祥老师,成为大祥老师
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务