在一个排序矩阵中找从小到大的第 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;
}
}
}
}