Middle-题目101:332. 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.
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.
题目大意:
给出一系列机票的列表,用一个二元组[from,to]表示。重新构造出一个从”JFK”出发的旅行线路。如果有多个解,求字典序最小的。
题目分析:
先将机票列表构造成邻接表,其中邻接列表部分使用优先队列维护字典序,然后从”JFK”点开始搜索,每次取出优先队列的队首节点(字典序最小)并再次搜索,直到某个节点的优先队列为空时将当前节点加入线路列表的头部(因为最后一个节点也是最后一个旅行到的节点,应是在表尾的)
源码:(language:java)

public class Solution {
    LinkedList<String> res;
    Map<String, PriorityQueue<String>> mp;

    public List<String> findItinerary(String[][] tickets) {
        res = new LinkedList<String>();
        mp = new HashMap<String, PriorityQueue<String>>();
        for (String[] ticket : tickets) {
            if (!mp.containsKey(ticket[0])) {
                mp.put(ticket[0], new PriorityQueue<String>());
            }
            mp.get(ticket[0]).offer(ticket[1]);
        }
        dfs("JFK");
        return res;
    }

    public void dfs(String cur) {
        while (mp.containsKey(cur) && !mp.get(cur).isEmpty()) {
            dfs(mp.get(cur).poll());
        }
        res.addFirst(cur);
    }
}

成绩:
12ms,beats 81.78%,众数14ms,12.37%
Cmershen的碎碎念:
一开始使用的朴素的dfs解法,每次搜到解则比较字典序,并更新列表,但会超时。而这个算法的本质是贪心法,因为每次拿出字典序最小的点时,如果有解则一定是最优解。(假设邻接表中某个节点对应优先队列是(…p1,…p2…),p1

你可能感兴趣的:(Middle-题目101:332. Reconstruct Itinerary)