Kth Smallest Number in Sorted Matrix
ID: 401; medium
Solution 1 (Java)
public class Solution {
class Pair {
int x, y, val;
public Pair(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
}
/**
* @param matrix: a matrix of integers
* @param k: An integer
* @return: the kth smallest number in the matrix
*/
public int kthSmallest(int[][] matrix, int k) {
int[] dx = {0, 1};
int[] dy = {1, 0};
int n = matrix.length, m = matrix[0].length;
boolean[][] visited = new boolean[n][m];
Queue<Pair> minHeap = new PriorityQueue<>(new Comparator<Pair>() {
public int compare(Pair p1, Pair p2) {
return p1.val - p2.val;
}
});
minHeap.offer(new Pair(0, 0, matrix[0][0]));
for (int i = 0; i < k - 1; i++) {
Pair curr = minHeap.poll();
for (int j = 0; j < 2; j++) {
int next_x = curr.x + dx[j];
int next_y = curr.y + dy[j];
if (next_x < n && next_y < m && !visited[next_x][next_y]) {
Pair next = new Pair(next_x, next_y, matrix[next_x][next_y]);
minHeap.offer(next);
visited[next_x][next_y] = true;
}
}
}
return minHeap.peek().val;
}
}Notes
Solution 2 (Java)
Notes
Last updated