原题链接:378. 有序矩阵中第 K 小的元素
solution:
二分查找,从矩阵做下角元素开始查找,统计每次比mid小的个数。如果小于k则l = mid + 1,如果大于等于k,则r = mid;
class Solution {
public:
vector<vector<int>> ma;
int count(int m,int n,int mid) {
int i = m - 1,j = 0;
int cnt = 0;
while(i >= 0 && j <= n - 1) {
if(ma[i][j] <= mid) {
cnt += i + 1;
j++;
}
else i--;
}
return cnt;
}
int kthSmallest(vector<vector<int>>& matrix, int k) {
ma = matrix;
int m = matrix.size();
int n = matrix.size();
int l = matrix[0][0];
int r = matrix[m - 1][n - 1];
while(l < r) {
int mid = l + (r - l) / 2;
if(count(m,n,mid) < k) l = mid + 1;
else r = mid;
}
return l;
}
};