Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. You must find a solution with complexity better than O(n2).

  Example 1:
  Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
 
  构建一个优先队列,底层是一个大顶堆,最大的元素会排在前面,同时维护这个优先队列的长度为k,从而可以得到第k小的元素 如果是小顶堆的话,需要传入仿函数,构造新的排序准则,从而得到第k大的元素。

class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) { priority_queue<int> dp;
for(int i=0;i<matrix.size();++i){
for(int j=0;j<matrix[0].size();++j){ dp.push(matrix[i][j]);
if(dp.size()>k) dp.pop(); }
}
return dp.top(); }
};

  

最新文章

  1. SQL 高效分页查询
  2. Echarts源码总括
  3. linux终端快捷键
  4. javascript权威指南笔记--javascript语言核心(三)
  5. Hadoop 重启各个节点
  6. duplicate symbols
  7. Mayan游戏 (codevs 1136)题解
  8. iOS开发——路径篇&amp;混编路径与全局宏路径
  9. 为什么Wireshark无法解密HTTPS数据
  10. Codeforces Round #363 (Div. 2)-&gt;B. One Bomb
  11. ShowcaseView-master
  12. linux下mysql数据库的操作
  13. 一个JAVA代码
  14. Android Studio怎样安装插件
  15. iOS混合应用开发入门
  16. “字符串替换” 和 “模板设置” (application/config.php)
  17. Pythonic
  18. word模板导出的几种方式:第三种:标签替换(DocX组件读取与写入Word)
  19. QWaitConditioin的思考1
  20. WindowsPE权威指南 第二章 小工具 pedump代码的C语言实现

热门文章

  1. MySQL高级篇 | 分析sql性能
  2. DASCTF 安恒七月赛wp
  3. Azure Virtual NetWoker(一)对等互连网络
  4. feignclient各种使用技巧说明
  5. 9组-Ahlpa-6/3
  6. Spring Aop面向切面编程&amp;&amp;自动注入
  7. [luogu5423]Valleys
  8. 多线程01.newThread的方式创建线程
  9. .net core 和 WPF 开发升讯威在线客服系统:使用本地IP数据库实现访客来源快速定位,支持国外
  10. Python 3 快速入门 3 —— 模块与类