Kth Smallest Number in Sorted Matrix
Example
Input:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
k = 4
Output: 5Input:
[
[1, 2],
[3, 4]
]
k = 3
Output: 3Note
Code
Last updated
Input:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
k = 4
Output: 5Input:
[
[1, 2],
[3, 4]
]
k = 3
Output: 3Last updated
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]public class Solution {
/**
* @param matrix: a matrix of integers
* @param k: An integer
* @return: the kth smallest number in the matrix
*/
private static class Node {
int x, y, val;
public Node(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
}
private final int[][] DIR = new int[][]{{1, 0}, {0, 1}};
public int kthSmallest(int[][] matrix, int k) {
// write your code here
if (matrix == null || matrix.length == 0 ||
matrix[0] == null || matrix[0].length == 0 || k <= 0) {
throw new IllegalArgumentException();
}
int m = matrix.length, n = matrix[0].length;
boolean[][] visited = new boolean[m][n];
Queue<Node> pq = new PriorityQueue<>((a,b) -> a.val - b.val);
pq.offer(new Node(0, 0, matrix[0][0]));
for (int i = 0; i < k - 1; i++) {
Node curr = pq.poll();
for (int dir = 0; dir < 2; dir++) {
int x = curr.x + DIR[dir][0];
int y = curr.y + DIR[dir][1];
if (x < m && y < n && !visited[x][y]) {
visited[x][y] = true;
pq.offer(new Node(x, y, matrix[x][y]));
}
}
}
return pq.poll().val;
}
}