Binary Search:378. Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:制作视频字幕软件 编辑:程序博客网 时间:2024/06/06 04:04
这道题让我们求有序矩阵中第K小的元素。我们使用一个最大堆,然后遍历数组每一个元素,将其加入堆,根据最大堆的性质,大的元素会排到最前面,然后我们看当前堆中的元素个数是否大于k,大于的话就将首元素去掉,循环结束后我们返回堆中的首元素即为所求。
class Solution {public: int kthSmallest(vector<vector<int>>& matrix, int k) { priority_queue<int> q; for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[i].size(); ++j) { q.emplace(matrix[i][j]); if (q.size() > k) q.pop(); } } return q.top(); }};
我的方法比较笨,放到一个vector里然后一起排序。
class Solution {public: int kthSmallest(vector<vector<int>>& matrix, int k) { vector<int> v; for(auto a : matrix) { for(auto x : a) { v.push_back(x); } } sort(v.begin(), v.end()); return v[k-1]; }};
阅读全文
0 0
- Binary Search:378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix-binary search/heap
- leetcode :Binary Search:Kth Smallest Element in a Sorted Matrix(378)
- 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
- 378. 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
- leecode 378. Kth Smallest Element in a Sorted Matrix java
- 378. Kth Smallest Element in a Sorted Matrix
- Java NIO
- 前端各种手写简易工具库
- Mybatis传多个参数的bug
- 滤波器设计(2):经典FIR数字滤波器的设计
- linux下vsftpd服务搭建
- Binary Search:378. Kth Smallest Element in a Sorted Matrix
- linux目录结构
- 关于组织的几个结论
- http协议中的状态码
- 基于Matlab中FDATool工具箱的滤波器设计及相关文件的生成
- 关于CI-CodeIgniter目录访问权限的问题的解决方法,通过修改.htaccess文件的办法解决无法加载css文件,js文件,图片文件等类型文件的方法
- 循环队列
- synchronized和ReentrantLock的区别
- java 高并发程序设计-附录