[LeetCode] Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素
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.
小顶堆实现:主要原理是弹出k - 1个比他小的 最后堆顶的就是第k小的 o1-o2 正负是对于o2而言的标准
大顶堆:最后留下k个元素,堆定就是需要的 o2-o1
这里用的小顶堆,首先 把第一行的元素全部加进去,实现一个堆。第二步:由于是每行顺序排列,弹出的堆顶元素也会根据每行顺序依次弹出,故只需要t.x再加一就得到下一行的元素,比如可以t.1+1, t.2+1,执行k-1次就找到第k小的元素了。当然需要判断有没有到最后一行,到了就无需再加。
public int kthSmallest(int[][] matrix, int k) {
int m = matrix.length, n = matrix[0].length;
PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
for(int j = 0; j < n; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
for(int i = 0; i < k - 1; i++) { // 小根堆,去掉 k - 1 个堆顶元素,此时堆顶元素就是第 k 的数
Tuple t = pq.poll();
if(t.x == m - 1) continue;
pq.offer(new Tuple(t.x + 1, t.y, matrix[t.x + 1][t.y]));
}
return pq.poll().val;
}
class Tuple implements Comparable<Tuple> {
int x, y, val;
public Tuple(int x, int y, int val) {
this.x = x; this.y = y; this.val = val;
}
@Override
public int compareTo(Tuple that) {
return this.val - that.val;
}
}
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int m = matrix.length, n = matrix[0].length;
PriorityQueue<Tuple> pq = new PriorityQueue<>();
for(int i = 0; i < n; i++)
pq.add(new Tuple(0, i, matrix[0][i]));
for(int j = 0; j < k-1; j++){
Tuple t = pq.poll();
if(t.x == m - 1)
continue;
pq.add(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
}
return pq.poll().val;
}
class Tuple implements Comparable<Tuple>{
int x, y, val;
public Tuple(int x, int y, int val){
this.x = x;
this.y = y;
this.val = val;
}
public int compareTo(Tuple that){
return this.val - that.val;
}
}
}