本文主要是介绍Reconstruct Itinerary,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一道好题,要常做常新。当中犯了两个错误:
1. 对于[["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]],会有这样的错误: ["JFK","KUL","NRT","JFK"]
2. 对于sjc,是没有queue的,所以必须判断queue为空的情况
public class Solution {List<String> res = new LinkedList<>();Map<String, PriorityQueue<String>> map = new HashMap<>();public List<String> findItinerary(String[][] tickets) {if (tickets == null || tickets.length == 0 || tickets[0].length == 0) {return res;}for (String[] ticket: tickets) {if (!map.containsKey(ticket[0])) {PriorityQueue<String> queue = new PriorityQueue<>();map.put(ticket[0], queue);}map.get(ticket[0]).offer(ticket[1]);}dfs("JFK");return res;}private void dfs(String str) {//1 res.add(str);PriorityQueue<String> queue = map.get(str);//2 while (!queue.isEmpty()) {while (queue != null && !queue.isEmpty()) {dfs(queue.poll());}res.add(0, str);}
}
这篇关于Reconstruct Itinerary的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!