Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int l = matrix[0][0];
int r = matrix.back().back();
while (l < r) {
int m = l + (r - l) / 2;
int cnt = 0; // 记录不大于 m 的元素数
for (auto& x : matrix) {
cnt += upper_bound(begin(x), end(x), m) - begin(x);
}
if (k <= cnt) {
r = m;
} else {
l = m + 1;
}
}
return l;
}
};