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.
思路
二分查找的变种
在这道题中,一定是matrix的第一个元素最小, martrix的最后一个元素最大
1.用min和max记录下最小值和最大值
2.算出mid之后,计算矩阵中有多少个比mid小的数字【num】
3.如果num大于k,那么重新界定max = mid;
如果num小于k,那么重新界定min = mid + 1;
int kthSmallest(int** matrix, int matrixRowSize, int matrixColSize, int k) {
int min = matrix[0][0], max = matrix[matrixRowSize - 1][matrixColSize - 1], mid;
while(min < max){
mid = (min + max) / 2;
int num = 0;
for(int i = 0; i < matrixRowSize; i++){
int row = 0;
for(int j = 0; j < matrixColSize; j++){
if(matrix[i][j] <= mid){
row++;
}else{
break;
}
}
num += row;
}
if(num < k) min = mid + 1;
else max = mid;
}
return min;
}