Skip to content

Latest commit

 

History

History
54 lines (50 loc) · 1.41 KB

23.md

File metadata and controls

54 lines (50 loc) · 1.41 KB

python2

  • 92ms
  • 82%
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists):
        from heapq import heappop, heappush, heapreplace, heapify
        heapList = [(n.val, n) for n in lists if n]
        heapify(heapList)
        dummy = cur = ListNode(0)
        while heapList:
            val, node = heapList[0]
            if node.next is None:
                heappop(heapList)
            else:
                heapreplace(heapList, (node.next.val, node.next))
            cur.next = node
            cur = cur.next
        return dummy.next

python3

  • 100ms
  • 77.58%
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        from heapq import heappop, heappush, heapreplace, heapify
        heapList = [(n.val, i, n) for i, n in enumerate(lists) if n]
        heapify(heapList)
        dummy = cur = ListNode(0)
        while heapList:
            val, i, node = heapList[0]
            if node.next is None:
                heappop(heapList)
            else:
                heapreplace(heapList, (node.next.val, i, node.next))
            cur.next = node
            cur = cur.next
        return dummy.next