Leetcode - 378 Kth Smallest Element in a Sorted Matrix (Medium)
题目描述:矩阵的每一行与每一列均递增,找出第 k 个元素。
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
解法一:二分查找。
public int kthSmallest(int[][] matrix, int k) {
int m = matrix.length, n = matrix[0].length;
int lo = matrix[0][0], hi = matrix[m - 1][n - 1] + 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n && matrix[i][j] <= mid; j++) {
count++;
}
}
if (count < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
解法二:堆。
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
for(int j = 0; j <= n - 1; j++)
pq.offer(new Tuple(0, j, matrix[0][j]));
for(int i = 0; i < k - 1; i++) {
Tuple t = pq.poll();
if(t.x == n - 1) continue;
pq.offer(new Tuple(t.x + 1, t.y, matrix[t.x + 1][t.y]));
}
return pq.poll().val;
}
}
class Tuple implements Comparable<Tuple> {
int x, y, val;
public Tuple (int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
@Override
public int compareTo (Tuple that) {
return this.val - that.val;
}
}