题意: 在一个二维数组中按行有序,按列也有序,在这个二维数组中找第k大的数
思路: 使用最小堆的思想。在最小堆中找到第k个数
实现方法: 利用java中自带的优先队列实现最小堆的思想
具体代码实现:
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int result = 0;
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (o1 > o2) {
return 1;
} else {
return -1;
}
}
});
int row = matrix.length;
int colum = matrix[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < colum; j++) {
queue.add(matrix[i][j]);
}
}
if (row * colum >= k) {
for (int i = 1; i < k; i++) {
queue.poll();
}
}
result = queue.peek();
return result;
}
}