Skip to content

Commit 6e116a1

Browse files
committed
Time: 215 ms (34.78%), Space: 45.9 MB (15.95%) - LeetHub
1 parent af8088c commit 6e116a1

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
private List<List<int[]>> graph;
3+
4+
private int dijkstra(int n) {
5+
int[] dist = new int[n];
6+
Arrays.fill(dist, Integer.MAX_VALUE);
7+
dist[0] = 0;
8+
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
9+
pq.offer(new int[]{0, 0});
10+
11+
while (!pq.isEmpty()) {
12+
int[] ele = pq.poll();
13+
int cd = ele[0], node = ele[1];
14+
if (node == n - 1) return dist[n - 1];
15+
if (cd > dist[node]) continue;
16+
for (int[] neighbor : graph.get(node)) {
17+
int nbr = neighbor[0], wt = neighbor[1];
18+
if (cd + wt < dist[nbr]) {
19+
dist[nbr] = cd + wt;
20+
pq.offer(new int[]{cd + wt, nbr});
21+
}
22+
}
23+
}
24+
return dist[n - 1];
25+
}
26+
27+
public int[] shortestDistanceAfterQueries(int n, int[][] queries) {
28+
graph = new ArrayList<>();
29+
for (int i = 0; i < n; i++) {
30+
graph.add(new ArrayList<>());
31+
}
32+
for (int i = 0; i < n - 1; i++) {
33+
graph.get(i).add(new int[]{i + 1, 1});
34+
}
35+
List<Integer> res = new ArrayList<>();
36+
for (int[] query : queries) {
37+
graph.get(query[0]).add(new int[]{query[1], 1});
38+
res.add(dijkstra(n));
39+
}
40+
return res.stream().mapToInt(i -> i).toArray();
41+
}
42+
}

0 commit comments

Comments
 (0)