【Leetcode】Reconstruct Itinerary
来源:互联网 发布:三菱plcfx3u编程手册 编辑:程序博客网 时间:2024/06/03 05:21
题目链接:
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.
思路:
实质是求欧拉通路,采用Hierholzer算法。
用优先队列(String默认字典序)保存每条边,建立邻接表。
DFS,按字典序访问邻居结点,访问的同时删除该边
算法:
HashMap<String, PriorityQueue<String>> maps = new HashMap<String, PriorityQueue<String>>(); LinkedList<String> res = new LinkedList<String>(); public List<String> findItinerary(String[][] tickets) { for (int i = 0; i < tickets.length; i++) { if (!maps.containsKey(tickets[i][0])) { PriorityQueue<String> p = new PriorityQueue<String>(); maps.put(tickets[i][0], p); } maps.get(tickets[i][0]).offer(tickets[i][1]); } dsp("JFK"); return res; } public void dsp(String s) { PriorityQueue<String> neibors = maps.get(s); while (neibors != null && !neibors.isEmpty()) { dsp(neibors.poll());// 访问某边就将该边删除 } res.addFirst(s); }
- leetcode Reconstruct Itinerary
- *[LeetCode]332. Reconstruct Itinerary
- leetcode 332. Reconstruct Itinerary
- [LeetCode 332] Reconstruct Itinerary
- LeetCode 332 : Reconstruct Itinerary
- leetcode笔记:Reconstruct Itinerary
- LeetCode *** 332. Reconstruct Itinerary
- leetcode reconstruct-itinerary
- LeetCode 332. Reconstruct Itinerary
- 【Leetcode】Reconstruct Itinerary
- LeetCode No332. Reconstruct Itinerary
- leetcode 332 Reconstruct Itinerary
- leetcode 332. Reconstruct Itinerary
- LeetCode[332] Reconstruct Itinerary
- [leetcode] 332. Reconstruct Itinerary
- Leetcode 332. Reconstruct Itinerary
- Leetcode 332. Reconstruct Itinerary
- [LeetCode] Reconstruct Itinerary
- 【Leetcode】Ugly Number II
- [HDU1588]Gauss Fibonacci(递推+矩阵快速幂)
- Markdown编辑器基本语法
- Unity 简单读取txt文档内容的方法
- 8-CSS选择器
- 【Leetcode】Reconstruct Itinerary
- 性能优化总结
- 第10.11-补充2-2
- IPSEC与SSL/TLS的比较
- 影响到Spark输出RDD分区的操作函数
- 【Leetcode】Minimum Height Trees
- 【Leetcode】Course Schedule
- 2016年上半年软考总结
- 【Leetcode】Course Schedule II