imashutosh51

Merge K sorted Lists

Jul 23rd, 2022 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. from heapq import heappush, heappop
  2. from typing import List, Optional
  3.  
  4. # Definition for singly-linked list.
  5. # class ListNode:
  6. #     def __init__(self, val=0, next=None):
  7. #         self.val = val
  8. #         self.next = next
  9.  
  10. class Solution:
  11.     def mergeKLists(self, lists: List[Optional['ListNode']]) -> Optional['ListNode']:
  12.         heap = []
  13.        
  14.         for i in range(len(lists)):
  15.             if lists[i]:
  16.                 heappush(heap, (lists[i].val, i, lists[i]))
  17.  
  18.         dummy = ListNode(0)
  19.         tail = dummy
  20.        
  21.         while heap:
  22.             val, i, node = heappop(heap)
  23.             tail.next = node
  24.             tail = tail.next
  25.  
  26.             if node.next:
  27.                 heappush(heap, (node.next.val, i, node.next))
  28.  
  29.         return dummy.next
  30.  
Advertisement
Add Comment
Please, Sign In to add comment