【LeetCode】332. Reconstruct Itinerary 重新安排行程(Medium)(JAVA)
题目地址: https://leetcode.com/problems/reconstruct-itinerary/
题目描述:
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.
- One must use all the tickets once and only once.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
题目大意
给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。
提示:
- 如果存在多种有效的行程,请你按字符自然排序返回最小的行程组合。例如,行程 [“JFK”, “LGA”] 与 [“JFK”, “LGB”] 相比就更小,排序更靠前
- 所有的机场都用三个大写字母表示(机场代码)。
- 假定所有机票至少存在一种合理的行程。
- 所有的机票必须都用一次 且 只能用一次。
解题方法
- 用一个 map 来存对应飞往的地方,目的地用优先队列来存,让字符顺序小的在前面
- 因为肯定存在一个解,所以优先遍历小的,然后遍历到结束,这样存在一个问题,可能小的这条路最终到了终点,但是有的没遍历过
- 所以我们采用逆序的方式,如果遍历到了死胡同,他就优先加入,最后翻转,就在最后了;如果没有遍历到死胡同,那就是刚好按照顺序遍历完了,加入的时候也是后加入的,翻转就是结果
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
if (tickets.size() == 0) return new ArrayList<>();
Map<String, PriorityQueue<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
for (int i = 0; i < tickets.size(); i++) {
PriorityQueue<String> temp = map.get(tickets.get(i).get(0));
if (temp == null) {
temp = new PriorityQueue<>();
map.put(tickets.get(i).get(0), temp);
}
temp.offer(tickets.get(i).get(1));
}
fH(map, list, "JFK");
Collections.reverse(list);
return list;
}
public void fH(Map<String, PriorityQueue<String>> map, List<String> list, String cur) {
PriorityQueue<String> nextQueue = map.get(cur);
while (nextQueue != null && nextQueue.size() > 0) {
fH(map, list, nextQueue.poll());
}
list.add(cur);
}
}
执行耗时:6 ms,击败了99.32% 的Java用户
内存消耗:39.2 MB,击败了77.96% 的Java用户
