LeetCode Reconstruct Itinerary
2016-03-23 01:23
344 查看
原题链接在这里:https://leetcode.com/problems/reconstruct-itinerary/
题目:
Given a list of airline tickets represented by pairs of departure and arrival airports
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
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
Return
Example 2:
Return
Another possible reconstruction is
题解:
把这些ticket当成edge构建directed graph. 为了保证字母顺序,用了PriorityQueue. 然后做dfs.
Time Complexity: O(n+e). Space: O(n+e).
AC Java:
题目:
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:
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.
题解:
把这些ticket当成edge构建directed graph. 为了保证字母顺序,用了PriorityQueue. 然后做dfs.
Time Complexity: O(n+e). Space: O(n+e).
AC Java:
public class Solution { Map<String, PriorityQueue<String>> graph = new HashMap<String, PriorityQueue<String>>(); public List<String> findItinerary(String[][] tickets) { List<String> res = new LinkedList<String>(); if(tickets == null || tickets.length == 0 || tickets[0].length == 0){ return res; } for(String [] edge : tickets){ if(!graph.containsKey(edge[0])){ graph.put(edge[0], new PriorityQueue<String>()); } graph.get(edge[0]).add(edge[1]); } dfs("JFK", res); return res; } private void dfs(String s, List<String> res){ while(graph.containsKey(s) && !graph.get(s).isEmpty()){ dfs(graph.get(s).poll(), res); } res.add(0, s); } }
相关文章推荐
- "locate: can not open `/var/lib/mlocate/mlocate.db"问题解决
- iOS 中的数据持久化2.0-bruceyou1990
- Android笔记之如何获取屏幕宽高
- Handler详解系列——利用Handler在主线程与子线程之间互发消息,handler详解
- 自定义模板引擎_4
- 公共技术点之面向对象六大原则
- hdoj2084 数塔
- 2015 Objective-C 三大新特性 不可错过的iOS开发技巧
- 程序使用微软雅黑作为默认字体在xp下的问题
- iOS动态分享收藏举报弹出框
- Android基础和运行机制
- java基础学习----String
- Android Listview 隐藏滚动条
- Android 65536问题
- OC与Swift混编
- npm 安装权限问题,在安装命令前加上,sudo即可
- kindeditor的使用方法简单介绍
- swift闭包--简明代码理解
- POJ 1979 && HDU 1312 Red and Black(DFS)
- i++原理分析