-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode378.java
More file actions
56 lines (50 loc) · 1.47 KB
/
LeetCode378.java
File metadata and controls
56 lines (50 loc) · 1.47 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
import java.util.PriorityQueue;
import java.util.Comparator;
public class LeetCode378 {
public static void main(String[] args) {
// 输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
// 输出:13
System.out
.println(new Solution378().kthSmallest(new int[][] { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } }, 8));
// 输入:matrix = [[-5]], k = 1
// 输出:-5
System.out
.println(new Solution378().kthSmallest(new int[][] { { -5 } }, 1));
}
}
class Solution378 {
static class Cell {
int i;
int j;
Cell(int i, int j) {
this.i = i;
this.j = j;
}
}
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Cell> pq = new PriorityQueue<>(new Comparator<>() {
@Override
public int compare(Cell c1, Cell c2) {
int val1 = matrix[c1.i][c1.j];
int val2 = matrix[c2.i][c2.j];
return Integer.compare(val1, val2);
}
});
int n = matrix.length;
for (int i = 0; i < n; i++) {
pq.offer(new Cell(i, 0));
}
Cell cur;
while (true) {
cur = pq.poll();
k--;
if (k == 0) {
break;
}
if (cur.j <= n - 2) {
pq.offer(new Cell(cur.i, cur.j + 1));
}
}
return matrix[cur.i][cur.j];
}
}