serega1112

378 - binary search

Dec 19th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. class Solution:
  2.     def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
  3.         n = len(matrix)
  4.         l = matrix[0][0] - 1
  5.         r = matrix[-1][-1]
  6.         res = r
  7.        
  8.         def count_less_than_x(x):
  9.             count = 0
  10.             max_elem = 0
  11.             i, j = n - 1, 0
  12.             while i >= 0 and j < n:
  13.                 if matrix[i][j] > x:
  14.                     i -= 1
  15.                 else:
  16.                     count += (i + 1)
  17.                     max_elem = max(max_elem, matrix[i][j])
  18.                     j += 1                
  19.             return count, max_elem
  20.            
  21.        
  22.         while r - l > 1:
  23.             mid = l + (r - l) // 2
  24.             count, val = count_less_than_x(mid)
  25.             if count < k:
  26.                 l = mid
  27.             else:
  28.                 r = mid
  29.                 res = val
  30.                
  31.         return res
Advertisement
Add Comment
Please, Sign In to add comment