您的位置:首页 > 其它

378. Kth Smallest Element in a Sorted Matrix

2016-12-03 17:46 369 查看
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 class Solution {
public int kthSmallest(int[][] matrix, int k) {
int m=matrix.length-1;
int n=matrix[0].length-1;

int l_v=matrix[0][0];
int h_v=matrix[m]
;
int count;
int mid;
int j;
while(l_v<h_v){
mid=l_v+(h_v-l_v)/2;
count=0;
for(int i=0;i<=m;i++){
j=n;
while(j>=0&&matrix[i][j]>mid)
j--;
count+=j+1;
}
if(count>=k)
h_v=mid;
else
l_v=mid+1;

}
return l_v;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: