给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是排序后的第 k 小元素,而不是第 k 个不同的元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
返回 13。
方法一:小根堆
class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>(){
public int compare(int[] o1,int[] o2){
return o1[0] - o2[0];
}
});
int n = matrix.length;
for(int i=0;i<n;i++){
queue.offer(new int[]{matrix[i][0],i,0});
}
for(int i=0;i<k-1;i++){
int temp[] = queue.poll();
if(temp[2] < n - 1){
queue.offer(new int[]{matrix[temp[1]][temp[2]+1],temp[1],temp[2] + 1});
}
}
return queue.poll()[0];
}
}
提示:
你可以假设 k 的值永远是有效的,1 ≤ k ≤ n2 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix