[LeetCode] 332. Reconstruct Itinerary Java
题目:
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to]
, reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK
. Thus, the itinerary must begin with JFK
.
Note:
- If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary
["JFK", "LGA"]
has a smaller lexical order than["JFK", "LGB"]
. - All airports are represented by three capital letters (IATA code).
- You may assume all tickets form at least one valid itinerary.
Example 1:tickets
= [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"]
.
Example 2:tickets
= [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"]
.
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]
. But it is larger in lexical order.
题意及分析:将所有的机票用数组保存起来,最后我们就是要找出一条路径将机票用完,并且如果有多条路径,就找字典序最小的。最开始想到的方法是用一个hashmap<String,PriorityQueue<String>>保存每个点及其邻节点,然后使用深度遍历,第一次得到的结果便是答案(因为每次都是用的最小路径)。 另外一种方法是每次找到终点,然后删除该点继续查找下一个终点,最后得到的结果反转即可。
代码:
public class Solution { Map<String, PriorityQueue<String>> map= new HashMap<>(); List<String> res = new ArrayList<>(); public List<String> findItinerary(String[][] tickets) { for(String[] ticket:tickets){ map.computeIfAbsent(ticket[0],k->new PriorityQueue<>()).add(ticket[1]); } dfs("JFK"); Collections.reverse(res); return res; } public void dfs(String node){ PriorityQueue<String> priorityQueue = map.get(node); while(priorityQueue!=null&&!priorityQueue.isEmpty()) dfs(priorityQueue.poll()); res.add(node); } }