对写LeetCode博客很有用的一个小插件

https://chrome.google.com/webstore/detail/leetcode-helper/gleoepapfjkpcijfmchfabbnldejdnoj/related
他会:
在这里插入图片描述

他会产生以下效果 可以说是非常棒了。(虽然下面的代码是错的 😦 )

332. Reconstruct Itinerary

Difficulty: Medium

Related Topics: Depth-first Search, Graph

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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets form at least one valid itinerary.
  4. One must use all the tickets once and only once.

Example 1:

Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
             But it is larger in lexical order.

Solution

Language: Java

class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        HashMap<String, List<String>> map = new HashMap<>();
        
        for (List<String> ticket: tickets) {
            map.computeIfAbsent(ticket.get(0), k -> new ArrayList<>());
            map.get(ticket.get(0)).add(ticket.get(1));
        }
        // we will using bfs but each time we only go with negihbor with minimum lexi, although for situations like this, it's better for us to implement dfs instead of bfs
        Queue<String> queue = new LinkedList<>();
        queue.offer("JFK");
        List<String> res = new ArrayList<>();
        res.add("JFK");
        //i don;t think visited will be useful, because we might revisited previous node, like we might need to return the JFK again in example
        while (!queue.isEmpty()) {
            String cur = queue.poll();
            if (!map.containsKey(cur)) { //we neeed to check if map contains this key in case it is the last one
                break;
            }
            int size = map.get(cur).size();
            String min = "ZZZ";
            for (int i = 0; i < size; i++) {
                if (map.get(cur).get(i).compareTo(min) < 0) {
                    min = map.get(cur).get(i);
                }
            }
            queue.offer(min);
            res.add(min);
        }
        return res;
        
    }
}
posted @ 2020-12-03 12:47  EvanMeetTheWorld  阅读(27)  评论(0)    收藏  举报