Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
二分搜索,但是以数据为范围而不是和平常一样以索引为范围
public int kthSmallest(int[][] matrix, int k) {
int n = matrix[0].length - 1;
int m = matrix.length - 1;
int l = matrix[0][0];
int r = matrix[m][n];
while(l < r){
int mid = l + (r - l) / 2;
int count = 0;
for(int i = 0; i <= m; i++){
int j = n;
while(j >= 0 && matrix[i][j] > mid) j--;
count += j + 1;
}
if(count < k) l = mid + 1;
else r = mid;
}
return l;
}