|
1 | 1 | 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; |
8 | 18 | }
|
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 |
| - } |
22 | 19 | }
|
0 commit comments