public int kthSmallest(int[][] matrix, int k) {
int len = matrix.length;
int low = matrix[0][0],high= matrix[len-1][len-1];
while(low<=high){
int mid = low + (high-low)/2;
int count = helper(matrix,mid);
if(count<k) low = mid+1;
else high = mid-1; //排除mid不在矩阵内的情况,所以只能等到low和high时才退出循环
}
return low;
}
private static int helper(int[][] matrix, int mid) {
// TODO Auto-generated method stub
int i = matrix.length-1,j=0;
int res = 0;
while(i>=0&&j<matrix[0].length){
if(matrix[i][j]>mid) i--;
else{
res+=i+1;
j++;
}
}
return res;
}
根据二分搜索法,获取中间值,然后搜索他是否为第k个值。
主要中间值不在矩阵内的情况。这就是
if(count<k) low = mid+1;
else high = mid-1;
这段语句的作用.
网友评论