Reconstruct Itinerary

来源:互联网 发布:linux wget 404 编辑:程序博客网 时间:2024/05/24 05:15


一道好题,要常做常新。当中犯了两个错误:

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);    }}


0 0