Advertisement
imashutosh51

Merge K sorted array

Jul 23rd, 2022 (edited)
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.46 KB | None | 0 0
  1. from heapq import heappush,heappop
  2. class Solution:
  3.     #Function to merge k sorted arrays.
  4.     def mergeKArrays(self, arr, K):
  5.         heap=[]
  6.         for i in arr:
  7.             heappush(heap,[i[0],0,i])
  8.         ans=[]
  9.         while len(heap)>0:
  10.             k=heappop(heap)
  11.             index=k[1]
  12.             ar=k[2]
  13.             ans.append(k[0])
  14.             if len(ar)>index+1:
  15.                 heappush(heap,[ar[index+1],index+1,ar])
  16.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement