zoukankan      html  css  js  c++  java
  • [LC] 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:

    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:

    Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
    Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]


    class Solution {
        public List<String> findItinerary(List<List<String>> tickets) {
            Map<String, PriorityQueue<String>> map = new HashMap<>();
            for (int i = 0; i < tickets.size(); i++) {
                List<String> curList = tickets.get(i);
                if (!map.containsKey(curList.get(0))) {
                    map.put(curList.get(0), new PriorityQueue<>());
                }
                map.get(curList.get(0)).add(curList.get(1));
            }
            List<String> res = new LinkedList<>();
            find("JFK", map, res);
            return res;
        }
        
        private void find(String start, Map<String, PriorityQueue<String>> map, List<String> res) {
            while (map.containsKey(start) && !map.get(start).isEmpty()) {
                String cur = map.get(start).poll();
                find(cur, map, res);
            }
            res.add(0, start);
        }
    }
  • 相关阅读:
    SOA the new OOP?
    请教一个程序装入执行的问题!
    程序员,如何选择合适的程序语言
    题解 P2387 【[NOI2014]魔法森林】
    题解 P4197 【Peaks】
    货车运输
    线段树合并
    jvm系列五java内存模型(2)
    jvm系列一什么是jvm
    jvm系列二内存结构
  • 原文地址:https://www.cnblogs.com/xuanlu/p/13058426.html
Copyright © 2011-2022 走看看