Advertisement
nikunjsoni

378

May 14th, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int kthSmallest(vector<vector<int>>& matrix, int k) {
  4.         int rows = matrix.size(), cols = matrix[0].size();
  5.         int l=matrix[0][0], r = matrix[rows-1][cols-1];
  6.        
  7.         int ans = 0;
  8.         while(l<r){
  9.             int mid = (l+r)/2;
  10.             int count = getCount(matrix, mid, rows, cols);
  11.             if(count < k)
  12.                 l = mid+1;
  13.             else
  14.                 r = mid;
  15.         }
  16.         return l;
  17.     }
  18.    
  19.     int getCount(vector<vector<int>>& matrix, int k, int rows, int cols){
  20.         int count = 0, curX = rows-1, curY = 0;
  21.         while(curX >= 0 && curY < cols){
  22.             if(matrix[curX][curY] > k)
  23.                 curX--;
  24.             else{
  25.                 count += (curX+1);
  26.                 curY++;
  27.             }
  28.         }
  29.         return count;
  30.     }
  31.    
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement