您的位置:首页 > 其它

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
[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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: