23. Merge k Sorted Lists [Hard]
# 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
网友评论