Kth Smallest Element in a Sorted Matrix问题及解法
来源:互联网 发布:反向代理 nginx 编辑:程序博客网 时间:2024/05/17 04:33
问题描述:
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.
示例:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15]],k = 8,return 13.
问题分析:
这题我们也可以用二分查找法来做,我们由于是有序矩阵,那么左上角的数字一定是最小的,而右下角的数字一定是最大的,所以这个是我们搜索的范围,然后我们算出中间数字mid。我们找到所有小于等于mid的值的元素个数,跟k进行比较,然后修改left和right,缩小搜索范围。我们注意到每列也是有序的,我们可以利用这个性质,从数组的左下角开始查找,如果比目标值小,我们就向右移一位,而且我们知道当前列的当前位置的上面所有的数字都小于目标值,那么cnt += i+1,反之则向上移一位,这样我们也能算出cnt的值。
过程详见代码:
class Solution {public: int kthSmallest(vector<vector<int>>& matrix, int k) {int left = matrix[0][0], right = matrix.back().back();while (left < right){int mid = left + (right - left) / 2;int cnt = search_less_equal(matrix,mid);if (cnt < k) left = mid + 1;else right = mid;}return left;}int search_less_equal(vector<vector<int>> matrix, int target){int n = matrix.size(), i = n - 1, j = 0, res = 0; while (i >= 0 && j < n){if (matrix[i][j] <= target){res += i + 1;j++;}else i--;}return res;}};
阅读全文
0 0
- Kth Smallest Element in a Sorted Matrix问题及解法
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a BST问题及解法
- 378. Kth Smallest Element in a Sorted Matrix
- 【Leetcode】Kth Smallest Element in a Sorted Matrix
- 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:378 Kth Smallest Element in a Sorted Matrix
- Fiddler抓包-抓APP的请求
- Oracle trunc()函数的用法简单使用
- AngularJS系列(二)——作用域和控制器
- iOS 之NSRange实现小数向上取整
- 锐利特科技物联网云平台解决方案
- Kth Smallest Element in a Sorted Matrix问题及解法
- Linux 的虚拟文件系统(强烈推荐)
- echarts 获取geojson中的数据
- 广西贺州市八步区领导干部前来梦想小镇参观学习
- 离线安装Cloudera Manager 5和CDH5(最新版5.1.3) 完全教程
- 【java笔试系列七】I/O整理
- Sublime Text 3 快捷键汇总
- windows/linux网络工具
- js中的replaceAll的实现