378 Kth Smallest Element in a Sorted Matrix

1. Question

Given anxnmatrix 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:
1
matrix = [
2
[ 1, 5, 9],
3
[10, 11, 13],
4
[12, 13, 15]
5
],
6
k = 8,
7
8
return 13.
Copied!
Note: You may assume k is always valid, 1 ≤ k ≤ n^2.

2. Implementation

(1) Binary Search
思路: 为什么二分法的结果是正确的呢? 首先在二分法,我们知道要第k小的数一定在矩阵里,也即start <= res <= end, 而二分结束的条件是start >= end, 所以start == right == res。
1
class Solution {
2
public int kthSmallest(int[][] matrix, int k) {
3
if (matrix == null || matrix.length == 0 || k < 0) {
4
return -1;
5
}
6
7
int m = matrix.length, n = matrix[0].length;
8
9
int start = matrix[0][0], end = matrix[m - 1][n - 1], mid = 0;
10
int count = 0;
11
12
while (start < end) {
13
mid = start + (end - start) / 2;
14
count = searchAndCount(mid, matrix);
15
16
if (count < k) {
17
start = mid + 1;
18
}
19
else {
20
end = mid;
21
}
22
}
23
24
return start;
25
}
26
27
public int searchAndCount(int num, int[][] matrix) {
28
int row = matrix.length - 1, col = 0, count = 0;
29
30
while (row >= 0 && col < matrix[0].length) {
31
if (matrix[row][col] <= num) {
32
count += (row + 1);
33
++col;
34
}
35
else {
36
--row;
37
}
38
}
39
return count;
40
}
41
}
Copied!
(2) Heap
1
class Solution {
2
public int kthSmallest(int[][] matrix, int k) {
3
int n = matrix.length;
4
PriorityQueue<CellInfo> minHeap = new PriorityQueue<>();
5
6
for (int j = 0; j < n; j++) {
7
minHeap.add(new CellInfo(0, j, matrix[0][j]));
8
}
9
10
for (int i = 1; i < Math.min(k, n * n); i++) {
11
CellInfo curCell = minHeap.remove();
12
13
int curRow = curCell.row;
14
int curCol = curCell.col;
15
16
if (curRow + 1 < n) {
17
minHeap.add(new CellInfo(curRow + 1, curCol, matrix[curRow + 1][curCol]));
18
}
19
}
20
return minHeap.peek().val;
21
}
22
23
class CellInfo implements Comparable<CellInfo> {
24
int row;
25
int col;
26
int val;
27
28
public CellInfo(int row, int col, int val) {
29
this.row = row;
30
this.col = col;
31
this.val = val;
32
}
33
34
public int compareTo(CellInfo that) {
35
return this.val - that.val;
36
}
37
}
38
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度O((m + n)log(S)), 其中S指的是search space,即矩阵中最小数到最大数的区间, 空间复杂度O(1)
Heap: 时间复杂度O(n^2 * logn), 空间复杂度O(n), heap最多存储n(列数)个matrix的元素