zoukankan      html  css  js  c++  java
  • LeetCode 332. Reconstruct Itinerary

    原题链接在这里:https://leetcode.com/problems/reconstruct-itinerary/description/

    题目:

    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.

    题解:

    Eulerian path. 把这些ticket当成edge构建directed graph. 保证每条edge 只走一遍.

    为了保证字母顺序,用了PriorityQueue.

    然后做dfs. dfs 时注意 retrieve nodes backwards.

    Time Complexity: O(n+e). Space: O(n+e).

    AC Java:

     1 class Solution {
     2     public List<String> findItinerary(List<List<String>> tickets) {
     3         List<String> res = new ArrayList<>();
     4         if(tickets == null || tickets.size() == 0){
     5             return res;
     6         }
     7         
     8         HashMap<String, PriorityQueue<String>> graph = new HashMap<>();
     9         for(List<String> e : tickets){
    10             graph.putIfAbsent(e.get(0), new PriorityQueue<String>());
    11             graph.get(e.get(0)).add(e.get(1));
    12         }
    13         
    14         dfs("JFK", graph, res);
    15         return res;
    16     }
    17     
    18     private void dfs(String cur, HashMap<String, PriorityQueue<String>> graph, List<String> res){
    19         while(graph.containsKey(cur) && graph.get(cur).size() != 0){
    20             String next = graph.get(cur).poll();
    21             dfs(next, graph, res);
    22         }
    23         
    24         res.add(0, cur);
    25     }
    26 }
  • 相关阅读:
    WPF 下两种图片合成或加水印的方式(转载)
    Git reset与checkout的区别
    C# 串口导致电脑蓝屏一个可能的原因
    两个用于win7任务栏显示进度的dll
    批量远程执行shell命令工具
    基于zookeeper的主备切换方法
    代码的演变随记
    svn错误:Can't convert string from 'UTF-8' to native encoding
    not allowed to access to crontab because of pam configuration
    大数据利器
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5309418.html
Copyright © 2011-2022 走看看