Leetcode[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

  1. 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"].

DFS + Topological Sort

复杂度
O(N), O(N)

思路
重建graph,应为要按lexical order进行排序,所以用priorityqueue来决定下一个要poll出去的值。

代码

public List<String> findItinerary(String[][] tickets) {
    HashMap<String, PriorityQueue<String>> map = new HashMap<>();
    LinkedList<String> res = new LinkedList<>();
    for(int i = 0; i < tickets.length; i ++) {
        String key = tickets[i][0];
        if(map.get(key) == null) {
            map.put(key, new PriorityQueue<String>());
        }
        map.get(key).offer(tickets[i][1]);
    }
    //
    Stack<String> stack = new Stack<>();
    stack.push("JFK");
    while(!stack.isEmpty()) {
        String cur = stack.peek();
        if(map.containsKey(cur) && map.get(cur).size() > 0) {
            stack.push(map.get(cur).poll());
        }
        else {
            res.addFirst(stack.pop());
        }
    }
    return res;
}

hellolittleJ17
10 声望11 粉丝