K-way merge over rows
Time O(k log n) Space O(n)Push the first element of each row as (value, row, col). Pop k − 1 times, pushing the next element in that row each time. The top is the answer.
import java.util.PriorityQueue;
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
for (int r = 0; r < Math.min(n, k); r++) pq.offer(new int[]{matrix[r][0], r, 0});
for (int i = 0; i < k - 1; i++) {
int[] t = pq.poll();
if (t[2] + 1 < n) pq.offer(new int[]{matrix[t[1]][t[2] + 1], t[1], t[2] + 1});
}
return pq.peek()[0];
}
}Verdict: Direct use of the pattern.