https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
int kthSmallest(vector<vector<int>>& matrix, int k) {
int NI = matrix.size(), NJ = matrix[0].size();
int lo = matrix[0][0], hi = matrix[NI-1][NJ-1];
while(lo<hi) {
int mid = lo + (hi - lo) / 2;
int cnt = 0;
for(int i=0; i<NI; i++)
cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid)
- matrix[i].begin();
if(cnt < k) lo = mid+1;
else hi = mid;
}
return lo;
}
No comments:
Post a Comment