How to find Kth smallest element in a Sorted Matrix!?

Tease by Leetcode!!
        int n = matrix.size();
int low = matrix[0][0], high = matrix[n-1][n-1];

while(low < high) {
int mid = low + (high - low)/2;

if(count(matrix, mid) < k) low = mid + 1;
else high = mid;

}

example matrix :

1    5    7
10 11 13
12 14 18
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int low = matrix[0][0], high = matrix[n-1][n-1];

while(low < high) {
int mid = low + (high - low)/2;

if(count(matrix, mid) < k) low = mid + 1;
else high = mid;

}

return low;
}
int count(vector<vector<int>>& grid, int mid) {
int count = 0, n = grid.size();

for(int i=0; i<n; i++) {
for(int j = 0; j<n && grid[i][j] <= mid; j++) count++;
}

return count;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store