关闭

leetcode Reconsrtuct Itinerary

标签: leetcode算法
27人阅读 评论(0) 收藏 举报

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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. 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.

Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.

code:

public List<String> findItinerary(String[][] tickets) {
     List<String> list=new ArrayList<>();
    Map<String,Queue<String>> map=new HashMap<>();
    for(String[] str:tickets){
        if(map.get(str[0])==null){
            Queue<String> queue=new PriorityQueue<>(new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.compareTo(o2);
                }
            });
            queue.offer(str[1]);
            map.put(str[0],queue);
        }
        else map.get(str[0]).offer(str[1]);
    }
    Stack<String> stack=new Stack<>();
    stack.push("JFK");
    while(!stack.isEmpty()){
        while(map.containsKey(stack.peek())&&!map.get(stack.peek()).isEmpty()){
            stack.push(map.get(stack.peek()).poll());
        }
        list.add(0,stack.pop());
    }
    return list;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6791次
    • 积分:921
    • 等级:
    • 排名:千里之外
    • 原创:89篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类