-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKthSmallestElementInASortedMatrix.java
More file actions
61 lines (59 loc) · 2 KB
/
KthSmallestElementInASortedMatrix.java
File metadata and controls
61 lines (59 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package array_and_matrix;
/**
* @Author: Wenhang Chen
* @Description:给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
* 请注意,它是排序后的第k小元素,而不是第k个元素。
* <p>
* 示例:
* <p>
* matrix = [
* [ 1, 5, 9],
* [10, 11, 13],
* [12, 13, 15]
* ],
* k = 8,
* <p>
* 返回 13。
* @Date: Created in 10:10 2/1/2020
* @Modified by:
*/
public class KthSmallestElementInASortedMatrix {
// 参考https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/solution/er-fen-chao-ji-jian-dan-by-jacksu1024/
public int kthSmallest(int[][] matrix, int k) {
int row = matrix.length;
int col = matrix[0].length;
int left = matrix[0][0];
int right = matrix[row - 1][col - 1];
while (left < right) {
// 每次循环都保证第K小的数在left~right之间,当left==right,第k小的数就是left
int mid = (left + right) / 2;
// 找二维矩阵中<=mid的元素总个数
int count = findNotBiggerThanMid(matrix, mid, row, col);
if (count < k) {
// 第k小的数在右半部分,且不包含mid
left = mid + 1;
} else {
// 第k小的数在左半部分,可能包含mid
right = mid;
}
}
return right;
}
private int findNotBiggerThanMid(int[][] matrix, int mid, int row, int col) {
// 以列为单位找,找到每一列最后一个<=mid的数即知道每一列有多少个数<=mid
int i = row - 1;
int j = 0;
int count = 0;
while (i >= 0 && j < col) {
if (matrix[i][j] <= mid) {
// 第j列有i+1个元素<=mid
count += i + 1;
j++;
} else {
// 第j列目前的数大于mid,需要继续在当前列往上找
i--;
}
}
return count;
}
}