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 ≤ n^2.
代码
Approach #1 Recursive Approach
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> a[2] - b[2]);
for (int i = 0; i <= n - 1; i++) {
pq.offer(new int[]{0, i, matrix[0][i]});
}
for (int j = 0; j < k - 1; j ++) {
int[] tup = pq.poll();
int r = tup[0];
int c = tup[1];
if (r == n - 1) continue;
pq.offer(new int[] {r + 1, c, matrix[r + 1][c] });
}
return pq.poll()[2];
}
}
Approach #2 Binary Search
class Soltuion {
public int kthSmallest(int[][] matrix, int k) {
int row = matrix.length - 1;
int col = matrix[0].length - 1;
int lo = matrix[0][0];
int hi = matrix[row][col] + 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0, j = col;
for (int i = 0; i < row; i++) {
while (j >= 0 && matrix[i][j] > mid) j--;
count += (j + 1);
}
if (count < k) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
}