Leetcode: 332. Reconstruct Itinerary

Question:

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:

Input: [[“MUC”, “LHR”], [“JFK”, “MUC”], [“SFO”, “SJC”], [“LHR”, “SFO”]]
Output: [“JFK”, “MUC”, “LHR”, “SFO”, “SJC”]

Solution 1: Iteration by using stack

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
    	Map<String, PriorityQueue<String>> map = new HashMap<>();
    	List<String> route = new ArrayList<>();
    	for (List<String> ticket : tickets) {
    		map.computeIfAbsense(ticket.get(0), k -> new PriorityQueue()).add(ticket.get(1));
    	}
    	Stack<Spring> stack = new Stack<>();
    	stack.push("JFK");
    	while(!stack.isEmpty()) { // here we must put the while loop as the 
    	// out loop
    		while(map.containsKey(stack.peek()) && !map.get(stack.peek()).isEmpty()) {
    			stack.push(map.get(stack.peek()).poll());
    		}
    		route.add(0, stack.pop());
    	}
    	return route;
    }
}

Solution 2: Recursive Solution

class Solution {
	List<String> route = new ArrayList<>();
	Map<String, List<String>> map = new HashMap<>();
    public List<String> findItinerary(List<List<String>> tickets) {
    	for (List<String> ticket : tickets) {
    		map.countIfAbsense(ticket.get(0), k -> new PriorityQueue()).add(ticket.get(1));
    	}
    	visit("JFK");
    	return route;
    }
    public void visit(String airport) {
    	while (map.containsKey(airport) && !map.get(airport).isEmpty()) {
    		visit(map.get(airport).poll());
    	}
    	route.add(0, airport);
    }
}

Note:

Pay attention to the conditions in the while loop.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章