您的位置:首页 > 其它

378. Kth Smallest Element in a Sorted Matrix

2016-10-30 16:34 218 查看
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.

找出第n小的数。用堆排序,java中用优先队列。但是java默认的优先队列是大数在前 小数在后。要改成小数在前大数在后 这样才是第八小的数

注意这个比较器的实现

public class Solution {
public int kthSmallest(int[][] matrix, int k) {
// Queue<Integer> queue=new PriorityQueue<>();

PriorityQueue<Integer> queue = new PriorityQueue<>(k , new Comparator<Integer>(){
public int compare(Integer i1, Integer i2) {
return i2.intValue() - i1.intValue();
}
});

if(matrix.length==0||matrix==null) return 0;
int m=matrix.length;
int n=matrix[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
queue.add(matrix[i][j]);
if(queue.size()>k) queue.poll();
}
}
return queue.poll();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: