執行結果:
通過
顯示詳情
執行用時 :22 ms, 在所有 Java 提交中擊敗了33.63% 的用戶
內存消耗 :46.1 MB, 在所有 Java 提交中擊敗了6.18%的用戶
題目:
給定一個 n x n 矩陣,其中每行和每列元素均按升序排序,找到矩陣中第k小的元素。
請注意,它是排序後的第k小元素,而不是第k個元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
返回 13。
說明:
你可以假設 k 的值永遠是有效的, 1 ≤ k ≤ n2 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
未獲一個大小爲k的優先隊列,採用大頂堆。
大頂堆獲取最小的k個數,因爲每次都出去最大的。
小頂堆獲取最大的k個數,因爲每次都是出去最小的。
代碼:
class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Integer> queue=new PriorityQueue<>(new Comparator<Integer>(){
public int compare(Integer a,Integer b)
{
return b-a;
}
});
for(int i=0;i<matrix.length;i++)
{
for(int j=0;j<matrix[0].length;j++)
{
queue.add(matrix[i][j]);
if(queue.size()>k)
{
queue.poll();
}
}
}
return queue.poll();
}
}