LeetCode 378. Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:淘宝企业店铺开通流程 编辑:程序博客网 时间:2024/06/06 12:44
问题描述:
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.
Subscribe to see which companies asked this question.
之前写过一道类似的题,是搜索某个值,比较简单,这道题是搜索第k大的值,所以咋看起来很简单,但是解出来还是费了很多力气。因为没有限制复杂度,可以暴力排序,但是这样就没有意义了。后来参考了solution,有个二分查找的思路比较好:每次二分查找mid是第m大元素,如果m>k就在low-mid中查找,反之在mid-high中查找,不断循环mid=(low+high)/2,直到查找到m=k为止。其中中间的临界值的边界条件需要自习处理下,不然容易无限循环或者错过正确值。
代码:
class Solution {public:int kthSmallest(vector<vector<int>>& matrix, int k) {int n = matrix.size();int lo = matrix[0][0], hi = matrix[n - 1][n - 1];while (lo < hi) {int mid = (hi + lo) / 2;int c = 0;for (int i = 0; i < n; i++) {int j = 0;while (j < n && matrix[i][j] <= mid) j++;c += j;}if (c >= k) hi = mid;else lo = mid+1;}return lo;}};
阅读全文
0 0
- 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
- 378. [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笔记: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
- Centos7 FastDFS搭建
- 基于spring security及spring aop的权限控制
- Xcode编译出现linker command failed with exit code 1问题的解决方案
- linux的socket can学习,指令汇总:
- Android 自定义View 实现方向盘控件的绘制
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode Add to List 617 Merge Two Binary Trees (深度优先搜索)
- node js学习记录
- http与https请求
- 使用git向码云上提交代码
- java跨平台原理
- 音频帧率计算方法(为防止以后忘了)
- C#——面向对象——泛型——泛型接口
- redis哨兵模式