//有很多讨论,比如
// https://discuss.leetcode.com/topic/52865/my-solution-using-binary-search-in-c
// https://discuss.leetcode.com/topic/52912/binary-search-heap-and-sorting-comparison-with-concise-code-and-1-liners-python-72-ms
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
// 注意以下算法是直接按照整数范围>>1来进行二分查找的
int row = matrix.size(), col = matrix[0].size();
int small = matrix[0][0], big = matrix[row-1][col-1];
int mid;
while (small < big) {
mid = (small + big) >> 1;
int len = 0;
for (int i=0; i<row; ++i) {
len += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if (len < k) {
small = mid + 1;
}
else {
big = mid;
}
}
return small;
}
};