首页 > 学院 > 开发设计 > 正文

332. Reconstruct Itinerary

2019-11-06 07:12:27
字体:
来源:转载
供稿:网友

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.

public class Solution { public List<String> findItinerary(String[][] tickets) { Map<String, PriorityQueue<String>> map = new HashMap<String, PriorityQueue<String>>(); List<String> res = new ArrayList<String>(); Stack<String> stack = new Stack<String>(); stack.push("JFK"); for (String[] str : tickets) map.computeIfAbsent(str[0], k->new PriorityQueue()).add(str[1]); while (!stack.isEmpty()) { while (map.containsKey(stack.peek()) && !map.get(stack.peek()).isEmpty()) { stack.push(map.get(stack.peek()).poll()); } res.add(0, stack.pop()); } return res; }}
上一篇:2015.偶数求和

下一篇:如何写好状态机1

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表