DeepRest

Merge k Sorted Lists

Feb 5th, 2022
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.73 KB | None | 0 0
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. #     def __init__(self, val=0, next=None):
  4. #         self.val = val
  5. #         self.next = next
  6. class Solution:
  7.     def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
  8.         hp = []
  9.         for idx, head in enumerate(lists):
  10.             if head:
  11.                 heappush(hp, (head.val, idx))
  12.                 lists[idx] = head.next
  13.         tmp = dummy = ListNode()
  14.         while hp:
  15.             val, idx = heappop(hp)
  16.             tmp.next = ListNode(val)
  17.             tmp = tmp.next
  18.             if lists[idx] != None:
  19.                 heappush(hp, (lists[idx].val, idx))  
  20.                 lists[idx] = lists[idx].next
  21.         return dummy.next
Advertisement
Add Comment
Please, Sign In to add comment