Kth Smallest Element in a Sorted Matrix (Leetcode)二分法
来源:互联网 发布:java 线程安全的集合 编辑:程序博客网 时间:2024/05/29 20:01
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:
我们并不用对每一行都做二分搜索法,我们注意到每列也是有序的,我们可以利用这个性质,从数组的左下角开始查找,如果比目标值小,我们就向右移一位,而且我们知道当前列的当前位置的上面所有的数字都小于目标值,那么cnt += i+1,反之则向上移一位,这样我们也能算出cnt的值。其余部分跟上面的方法相同,参见代码如下:
JAVA代码:
public static int count(int[][] matrix,int target){
int i=matrix.length-1,j=0;
int res=0;
while(i>=0&&j<matrix[0].length){
if(matrix[i][j]>target)i--;
else{
res+=i+1;
j++;
}
}
return res;
}
public static int kthSmallest(int[][] matrix, int k) {
int left=matrix[0][0],right=matrix[matrix.length-1][matrix[0].length-1];
while(left<right){
int mid=(left+right)/2;
int cnt=count(matrix,mid);
if(cnt<k)left=mid+1;
else right=mid;
//System.out.println(left+" "+right+" "+mid+" "+cnt);
}
return left;
}
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15]],k = 8,return 13.
- Kth Smallest Element in a Sorted Matrix (Leetcode)二分法
- Kth Smallest Element in a Sorted Matrix (第十二周 二分法)
- 利用二分法解决 leetcode 378. Kth Smallest Element in a Sorted Matrix
- 【Leetcode】Kth Smallest Element in a Sorted Matrix
- LeetCode—378. Kth Smallest Element in a Sorted Matrix
- Leetcode 378. Kth Smallest Element in a Sorted Matrix
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 【leetcode】378. Kth Smallest Element in a Sorted Matrix
- LeetCode[378] Kth Smallest Element in a Sorted Matrix
- LeetCode:378 Kth Smallest Element in a Sorted Matrix
- leetcode之 Kth Smallest Element in a Sorted Matrix
- LeetCode:Kth Smallest Element in a Sorted Matrix
- leetcode---Kth Smallest Element in a Sorted Matrix
- 【Leetcode】378. Kth Smallest Element in a Sorted Matrix
- Leetcode-378. Kth Smallest Element in a Sorted Matrix
- leetCode No.378 Kth Smallest Element in a Sorted Matrix
- 378. [LeetCode]Kth Smallest Element in a Sorted Matrix
- 整形大整数乘法
- 分离目录路径和文件名
- 安卓开发 第十篇 使用Checkstyle规范代码
- shell脚本中echo显示内容带颜色显示
- Activity的四种模式
- Kth Smallest Element in a Sorted Matrix (Leetcode)二分法
- 安卓四大组件-----广播机制
- Weka连接MySQL数据库详解
- 蓝桥杯—分核桃
- 中国护照的几个小知识
- 学习总结:主席树
- 数字签名协议
- JSON.parse和JSON.stringify的区别
- VUE起步构建简单单页应用