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:
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();
}
}
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();
}
}
相关文章推荐
- 378.leetcode Kth Smallest Element in a Sorted Matrix(medium)[堆求第K小的 ]
- 378. Kth Smallest Element in a Sorted Matrix
- 【Leetcode】378. Kth Smallest Element in a Sorted Matrix
- leetcode 378. Kth Smallest Element in a Sorted Matrix有序矩阵寻找第K小数+二分查找
- Binary Search:378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix (Medium)
- LeetCode-378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378: Kth Smallest Element in Sorted Matrix
- ?378. Kth Smallest Element in a Sorted Matrix(Java)
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix