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.

矩阵元素按行按列递增有序,将matr[0][0]元素压进堆中,然后进行k-1次下面操作:

  取堆顶元素,将其在矩阵中的右边和下边的元素入堆,pop堆顶元素。

最后堆顶元素即是第k小的数。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std; struct Node
{
int x,y,num;
Node(int a,int b,int c)
{
x=a;
y=b;
num=c;
}
bool operator < (const Node& x)const
{
return num>x.num;
}
}; class Solution
{
public:
int kthSmallest(vector<vector<int> >& matrix, int k)
{
int len=matrix.size();
bool inheap[][];
memset(inheap,,sizeof(inheap));
priority_queue<Node> heap;
heap.push(Node(,,matrix[][]));
for(int i=; i<k-; i++)
{
Node now=heap.top();
if(now.x<len-&&inheap[now.x+][now.y]==)
{
heap.push(Node(now.x+,now.y,matrix[now.x+][now.y]));
inheap[now.x+][now.y]=;
}
if(now.y<len-&&inheap[now.x][now.y+]==)
{
heap.push(Node(now.x,now.y+,matrix[now.x][now.y+]));
inheap[now.x][now.y+]=;
}
heap.pop();
}
return heap.top().num;
}
};

最新文章

  1. 基于rem的移动端自适应解决方案
  2. 向jboss写入服务器日志
  3. Android之IPC机制
  4. 配置Pylint for Python3.5
  5. imx6 uboot lvds clock
  6. ASP.NET多次点击提交按钮以及Session超时和丢失过期问题
  7. 《javascript高级程序设计》对象图
  8. 动态规划(计数DP):HDU 5136 Yue Fei&#39;s Battle
  9. NOI2012 魔幻棋盘
  10. poj1716 Integer Intervals(差分约束)
  11. autoconf添加gcc调试选项
  12. idea+scala+spark遇到的一些问题
  13. C++ queue deque
  14. How 5 Natural Language Processing APIs Stack Up
  15. Rest API
  16. 【2019雅礼集训】【最大费用流】【模型转换】D2T3 sum
  17. 生成树的计数 Matrix-Tree(矩阵树)定理
  18. 开源WebGIS实施方案(六):空间数据(PostGIS)与GeoServer服务迁移
  19. django找不到模板(TemplateDoesNotExist at)的异常处理案例
  20. php中0与空 Null false的区别

热门文章

  1. 创建GitHub技术博客全攻略【转】
  2. 字符串输出输入函数,const修饰符,内存分区,动态内存管理,指针和函数,结构体
  3. hdu 5289(单调队列)
  4. AutoMapper封装类
  5. 使用root用户登录到AWS EC2服务器,上传文件到/var/www目录
  6. linux下tab键在命令行情况下的强大
  7. Allure对单测结果以及robotframework结果的处理
  8. shiro 登录
  9. java启动参数一
  10. 2017 JUST Programming Contest 3.0 B. Linear Algebra Test