[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"]
["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); } }
[LeetCode] 332. Reconstruct Itinerary Java