Skip to content

Commit 49a1a51

Browse files
authored
Update Reconstruct Itinerary.java
1 parent 9759e5a commit 49a1a51

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

Hard/Reconstruct Itinerary.java

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,19 @@
11
class Solution {
2-
public List<String> findItinerary(List<List<String>> tickets) {
3-
Map<String, PriorityQueue<String>> map = new HashMap<>();
4-
for (List<String> ticket : tickets) {
5-
String from = ticket.get(0);
6-
String to = ticket.get(1);
7-
map.computeIfAbsent(from, k -> new PriorityQueue<>()).add(to);
2+
public List<String> findItinerary(List<List<String>> tickets) {
3+
Map<String, PriorityQueue<String>> map = new HashMap<>();
4+
for (List<String> ticket : tickets) {
5+
map.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1));
6+
}
7+
Stack<String> stack = new Stack<>();
8+
stack.push("JFK");
9+
List<String> result = new ArrayList<>();
10+
while (!stack.isEmpty()) {
11+
while (map.containsKey(stack.peek()) && !map.get(stack.peek()).isEmpty()) {
12+
stack.push(map.get(stack.peek()).poll());
13+
}
14+
result.add(stack.pop());
15+
}
16+
Collections.reverse(result);
17+
return result;
818
}
9-
Stack<String> stack = new Stack<>();
10-
LinkedList<String> result = new LinkedList<>();
11-
stack.push("JFK");
12-
while (!stack.isEmpty()) {
13-
String destination = stack.peek();
14-
if (!map.getOrDefault(destination, new PriorityQueue<>()).isEmpty()) {
15-
stack.push(map.get(destination).remove());
16-
} else {
17-
result.addFirst(stack.pop());
18-
}
19-
}
20-
return result;
21-
}
2219
}

0 commit comments

Comments
 (0)