serega1112

378 - heap

Dec 17th, 2020 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.39 KB | None | 0 0
  1. class Solution:
  2.     def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
  3.         n = len(matrix)
  4.         h = [(matrix[i][0], i, 0) for i in range(n)]
  5.         heapq.heapify(h)
  6.         while k:
  7.             val, i, j = heapq.heappop(h)
  8.             if j < n - 1:  
  9.                 heapq.heappush(h, (matrix[i][j+1], i, j + 1))
  10.             k -= 1
  11.            
  12.         return val
Add Comment
Please, Sign In to add comment