Problem link: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
n == matrix.length
n == matrix[i].length ==> **count of rows == count of columns**
1 <= n <= 300
-109 <= matrix[i][j] <= 109
All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
1 <= k <= n2 ==> k is always valid
class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Node> pq = new PriorityQueue<>();
for (int c = 0; c < matrix[0].length; c++) {
pq.offer(new Node(0, c, matrix[0][c]));
}
int res = Integer.MAX_VALUE;
for (int i = 0; i < k; i++) {
Node minNode = pq.poll();
res = minNode.val;
if (minNode.row + 1 < matrix.length) {
Node nextNode = new Node(minNode.row + 1, minNode.col, matrix[minNode.row + 1][minNode.col]);
pq.offer(nextNode);
}
}
return res;
}
private class Node implements Comparable<Node> {
int row;
int col;
int val;
Node(int row, int col, int val) {
this.row = row;
this.col = col;
this.val = val;
}
@Override
public int compareTo(Node other) {
return this.val - other.val;
}
}
}
Kth Smallest Element in a Sorted Matric
原文:https://www.cnblogs.com/blackraven25/p/15100306.html