题目:排序矩阵中的从小到大第k个数
2015-10-24 22:40
197 查看
在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 k = 4 和一个排序矩阵:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
返回 5。
挑战
使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。
标签 Expand
相关题目 Expand
解题思路:
可以利用java自带的最小堆来进行每次选取最小的元素,一共选择K次就行了。
排序矩阵的定义为:每一行递增,每一列也递增。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 k = 4 和一个排序矩阵:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
返回 5。
挑战
使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。
标签 Expand
相关题目 Expand
解题思路:
可以利用java自带的最小堆来进行每次选取最小的元素,一共选择K次就行了。
public class Solution { /** * @param matrix * : a matrix of integers * @param k * : an integer * @return: the kth smallest number in the matrix */ class S { int row; int col; int val; public S(int row, int col, int val) { super(); this.row = row; this.col = col; this.val = val; } } public int kthSmallest(int[][] matrix, int k) { // write your code here int m = matrix.length; if (0 == m) return -1; int n = matrix[0].length; PriorityQueue<S> queue = new PriorityQueue<S>(n,new MyComparators()); for(int i=0;i<n;i++){ queue.add(new S(0, i, matrix[0][i])); } for(int i=0;i<k-1;i++){ S tmp = queue.poll(); if(tmp.row<m-1){ queue.add(new S(tmp.row+1, tmp.col,matrix[tmp.row+1][tmp.col])); } } return queue.poll().val; } @SuppressWarnings("unchecked") class MyComparators implements Comparator<S> { @Override public int compare(S o1, S o2) { // TODO Auto-generated method stub if (o1.val > o2.val) { return 1; } else if (o1.val == o2.val) { return 0; } else { return -1; } } } }
相关文章推荐
- 模态视图
- 通过Qt4.2样式表定制程序外观
- 从头认识java-3.1 for each
- mysql 的时间类型
- hdu4267 线段树
- EasyUI - NumberBox组件
- memcached分布式缓存服务器学习总结(四)php memcache扩展
- Java Web 技术整合基础篇1 web产生及发展
- Git学习笔记
- LeetCode60——Permutation Sequence
- Shell实现(三)读取命令的实现
- 面试题2015
- Python下载及Python环境变量的配置
- Android(4)布局方法、px/dp/dpi/ps/内边距与外边距
- linux基本命令三の管理进程
- 有关异常需要理解和注意的地方!!!
- 原子操作的实现原理
- CocoaPods的安装和使用介绍
- Android 工程目录结构简介
- Android 测试类型