LintCode "Kth Smallest Number in Sorted Matrix"
2015-11-06 15:50
369 查看
1AC! Yes! Intuitive thought will be: we walk from up-left to down-right - but we should only walk along the 'lowest edge' in the sorted matrix - so it is min-heap based BFS solution. Tricky, and really fun!
class Solution { struct Item { Item(): val(0), x(0), y(0){}; Item(int v, int xx, int yy): val(v), x(xx), y(yy){}; int val; int x; int y; // bool operator()(const Item &r1, const Item &r2) const { return r1.val > r2.val; } }; public: /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ int kthSmallest(vector<vector<int> > &m, int k) { int h = m.size(); int w = m[0].size(); vector<vector<bool>> rec(h, vector<bool>(w, false)); priority_queue<Item, std::vector<Item>, Item> q; int i = 0, j = 0; Item ret; q.push(Item(m[i][j], j, i)); rec[i][j] = true; while(k) { ret = q.top();q.pop(); j = ret.x; i = ret.y; if(i < (h - 1) && !rec[i + 1][j]) { q.push(Item(m[i + 1][j], j, i + 1)); rec[i + 1][j] = true; } if(j < (w - 1) && !rec[i][j + 1]) { q.push(Item(m[i][j + 1], j + 1, i)); rec[i][j + 1] = true; } k--; } return ret.val; } };
相关文章推荐
- makefile老是报“recipe for target xxx”错误,不妨先看看编码是否正确
- Android Studio插件-Android Butterknife Zelezny
- 洗牌算法
- 图像处理和图像识别中常用到的OpenCV函数
- Mapreduce不设置reduce,只执行map的输出结果
- ext,exrReturn新增,修改删除等用
- 快速开发平台为树型部件添加图标
- AES加密算法之轮密钥加操作
- JavaScript_JavaScript的闭包
- 直接插入排序
- 详解javascript数组去重问题
- Cloud Design Pattern - Competing Consumers(竞争消费模式)
- Unity3D通过对象池模式 管理场景中的元素
- GFS、HDFS等分布式文件系统对比介绍
- The method getDispatcherType() is undefined for the type HttpServletRequest解决办法
- uboot移植之配置分析
- eclipse导入java和android sdk源码,帮助文档
- docker新建ubuntu容器,设置ssh与物理机登陆
- XML中如果有特殊字符,比如> < 解决方案
- UVA-4288 Cat vs. Dog (最大独立集)