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.
首先第k大数一定落在[l, r]中,其中 l = matrix[0][0], r = matrix[row - 1][col - 1].
我们可以二分值域[l, r]区间,取中间值mid = l + (r - l) / 2, 需要注意mid值不一定在矩阵中,对于mid值,我们可以检查矩阵中有多少元素小于等于mid,
记个数为cnt,那么有:
1、如果cnt < k, 也就是说在值域[l, mid]中,包含的矩阵元素个数一定小于k,那么第k小元素一定不在值域[l, mid]中,所以更新l = mid + 1,去值域[mid + 1, r]中去寻找。
2、否则cnt >= k,那么在值域[l, mid]中,包含矩阵元素个数一定大于等于k,即第k小元素一定在值域[l,mid]中,更新r = mid;
那为什么不判断cnt =