serega1112

23 - heap

Dec 21st, 2020
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | None | 0 0
  1. class Solution:
  2.     def mergeKLists(self, lists: List[ListNode]) -> ListNode:
  3.        
  4.         h = [(node.val, random.random(), node) for node in lists if node]
  5.         heapq.heapify(h)
  6.         head = None
  7.         tail = None
  8.         while h:
  9.             _, _, node = heapq.heappop(h)
  10.             if head:
  11.                 tail.next = node
  12.                 tail = tail.next
  13.             else:
  14.                 head = node
  15.                 tail = node
  16.             if node.next:
  17.                 heapq.heappush(h, (node.next.val, random.random(), node.next))
  18.                
  19.         return head
Advertisement
Add Comment
Please, Sign In to add comment