23. Merge k Sorted Lists [Hard]

2019-10-10  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读