美文网首页
23. Merge k Sorted Lists [Hard]

23. Merge k Sorted Lists [Hard]

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-10-10 13:50 被阅读0次
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import heapq
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        def mylt(self, other):
            return self.val <= other.val
        setattr(ListNode, "__lt__", mylt)
        res = p = ListNode(0)
        heap = []
        for node in lists:
            if node:
                heapq.heappush(heap, node)
        while heap:
            node = heapq.heappop(heap)
            p.next = node
            p = p.next
            if node.next:
                heapq.heappush(heap, node.next)
        return res.next

相关文章

网友评论

      本文标题:23. Merge k Sorted Lists [Hard]

      本文链接:https://www.haomeiwen.com/subject/orgmyctx.html