leetcode练习 Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:如何清除mac桌面图标 编辑:程序博客网 时间:2024/06/06 03:59
依旧对第k大的数耿耿于怀
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 ≤
这道题的难点在于每行之间不一定是有序的
因此只能确定左上角和右下角的大小关系
再利用upper_bound的函数,就可以写出速度很快的算法
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, cnt = 0; for (int i = 0; i < matrix.size(); ++i) { cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin(); } if (cnt < k) left = mid + 1; else right = mid; } return left; }};
可以说是相当快了
阅读全文
0 0
- 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] 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
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- if __name__ == '__main__'的理解
- bootstrap-table行内编辑表格的实现
- Apache POI for Microsoft Office
- 排它平方数
- ADC0832作AD转换及串口显示程序
- leetcode练习 Kth Smallest Element in a Sorted Matrix
- 消息队列activemq小测试
- spring通过xml方式配置AOP时,提示错误信息:匹配的通配符是严格的,但是对于元素'aop:aspectj- 自动代理”。
- getParameter 与 getAttribute的区别
- 原码反码和补码区别
- springMVC的执行原理及与spring的关系
- HTTP请求中POST与GET的区别
- Java并发编程:Lock(包含synchronized的不足之处)
- Composer 安装