LeetCode 378. Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:网络交流 编辑:程序博客网 时间:2024/06/05 18:04
描述
找出矩阵中的第k小的数
解决
我想到的是使用multiset。
class Solution {public: int kthSmallest(vector<vector<int>>& matrix, int k) { multiset<int> res; int length = matrix.size(); for (int i = 0; i < length; ++i) { for (int j = 0; j < length; ++j) { res.insert(matrix[i][j]); } } int cnt = 1, zz = 0; for (auto it = res.begin(); it != res.end(); ++it, ++cnt) { if (k == cnt) { zz = *it; break; } } return zz; }};
另一种解法,参考:https://discuss.leetcode.com/topic/54528/clean-solution-with-detailed-explanation-in-c
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) { int length = matrix.size(); int l = matrix[0][0], r = matrix[length - 1][length - 1]; while (l < r) { int m = l + ((r - l) >> 1); int cnt = 0; for (int i = 0; i < length; ++i) { cnt += upper_bound(matrix[i].begin(), matrix[i].end(), m) - matrix[i].begin(); } if (cnt < k) { l = m + 1; } else { r = m; } } return l; }};
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
- PC110201:Jolly Jumpers
- javaScript总结
- GET和POST的区别
- 亲测可行ie8与ie11共存方法支持win7x64等
- 程序设计
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- libcurl,sqllite,log4cpp,openssl交叉编译
- ARM 处理器寻址方式
- Error contacting service. It is probably not running.
- fwrite和fread函数的用法小结
- html5 video播放队列
- Hadoop架构介绍——HDFS的体系结构
- VMware虚拟机安装win8系统提示:此主机支持Intel VT-x,但Intel VT-x处于禁用状态
- 程序员眼中的英语单词