Skip to content

Commit fef44ff

Browse files
authored
Update Reconstruct Itinerary.java
1 parent c1e28be commit fef44ff

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

Hard/Reconstruct Itinerary.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
class Solution {
22
public List<String> findItinerary(List<List<String>> tickets) {
3-
LinkedList<String> itinerary = new LinkedList<>();
4-
Map<String, PriorityQueue<String>> graph = new HashMap<>();
5-
Stack<String> stack = new Stack<>();
3+
Map<String, PriorityQueue<String>> map = new HashMap<>();
64
for (List<String> ticket : tickets) {
7-
graph.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1));
5+
String from = ticket.get(0);
6+
String to = ticket.get(1);
7+
map.computeIfAbsent(from, k -> new PriorityQueue<>()).add(to);
88
}
9+
Stack<String> stack = new Stack<>();
10+
LinkedList<String> result = new LinkedList<>();
911
stack.push("JFK");
1012
while (!stack.isEmpty()) {
11-
String nextDestination = stack.peek();
12-
if (!graph.getOrDefault(nextDestination, new PriorityQueue<>()).isEmpty()) {
13-
stack.push(graph.get(nextDestination).poll());
13+
String destination = stack.peek();
14+
if (!map.getOrDefault(destination, new PriorityQueue<>()).isEmpty()) {
15+
stack.push(map.get(destination).remove());
1416
} else {
15-
itinerary.addFirst(stack.pop());
17+
result.addFirst(stack.pop());
1618
}
1719
}
18-
return itinerary;
20+
return result;
1921
}
2022
}

0 commit comments

Comments
 (0)