-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHEAP_LC378
More file actions
41 lines (37 loc) · 986 Bytes
/
Copy pathHEAP_LC378
File metadata and controls
41 lines (37 loc) · 986 Bytes
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
class Solution {
class Node {
int value;
int row;
int col;
Node(int value, int row, int col) {
this.value = value;
this.row = row;
this.col = col;
}
}
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<Node> minHeap = new PriorityQueue<>(
(a, b) -> a.value - b.value
);
for (int i = 0; i < n; i++) {
minHeap.offer(new Node(matrix[i][0], i, 0));
}
int ans = 0;
while (k > 0) {
Node curr = minHeap.poll();
ans = curr.value;
k--;
if (curr.col + 1 < n) {
minHeap.offer(
new Node(
matrix[curr.row][curr.col + 1],
curr.row,
curr.col + 1
)
);
}
}
return ans;
}
}