一道好题,要常做常新。当中犯了两个错误:
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);
}
}

本文探讨了一个行程重构算法的具体实现,该算法使用优先队列来确保每次访问的都是当前机场可能前往的下一个最“小”的目的地。文章中提到了两种特殊情况:一种是当存在闭环时如何正确处理,另一种是没有出港航班的机场应该如何对待。通过具体的代码示例,展示了如何避免这两种常见的错误。
507

被折叠的 条评论
为什么被折叠?



