摘要:復雜度思路重建,應為要按進行排序,所以用來決定下一個要出去的值。
Leetcode[332] Reconstruct Itinerary
DFS + Topological SortGiven 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 singleFor 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"].
復雜度
O(N), O(N)
思路
重建graph,應為要按lexical order進行排序,所以用priorityqueue來決定下一個要poll出去的值。
代碼
public ListfindItinerary(String[][] tickets) { HashMap > map = new HashMap<>(); LinkedList res = new LinkedList<>(); for(int i = 0; i < tickets.length; i ++) { String key = tickets[i][0]; if(map.get(key) == null) { map.put(key, new PriorityQueue ()); } map.get(key).offer(tickets[i][1]); } // Stack stack = new Stack<>(); stack.push("JFK"); while(!stack.isEmpty()) { String cur = stack.peek(); if(map.containsKey(cur) && map.get(cur).size() > 0) { stack.push(map.get(cur).poll()); } else { res.addFirst(stack.pop()); } } return res; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/66138.html
摘要:題目解答都是用來解,一個用一個用來實現(xiàn)深度優(yōu)先搜索,搜索到一個城市只是的時候即沒有出度的時候,把這個記入中去,因為它肯定是最后到達的城市,然后依次向前類推的要求在存入的時候就用先存好先進去的說明是出發(fā)城市,那么最先出發(fā)的城市最后出來 題目:Given a list of airline tickets represented by pairs of departure and arri...
摘要:來自大神的解答,只能膜拜。題目確定了至少有一條的行程不存在分支情況,一定有相同的最終目的地,而且對于多條的行程,要選取字母順序較小的一條。 Problem Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the i...
摘要:如對應的英文表達為并繼續(xù)亂序成。要求輸入亂序的英文表達式,找出其中包含的所有的數(shù)字,并按照從小到大輸出。思路和代碼首先將數(shù)字和英文表示列出來粗略一看,我們知道有許多字母只在一個英文數(shù)字中出現(xiàn),比如只出現(xiàn)在中。 題目要求 Given a non-empty string containing an out-of-order English representation of digits...
摘要:題目要求假設有一組人站成一堆,每個人都記錄下了自己的高度,以及在自己前面有多少個不比自己矮的人。現(xiàn)在請按照這個信息將這組人放在隊列中正確的位置上并返回。但是這樣解決其實復雜化了問題。即越大,則該同等高度的人一定在另一個同等高度的人后面。 題目要求 Suppose you have a random list of people standing in a queue. Each per...
摘要:這里要注意的是的用法。所以記住,用可以從自動分離出數(shù)組。跳過第一個元素并放入數(shù)組最快捷語句建立的用意記錄處理過的結(jié)點并按處理所有結(jié)點和自己的連接下面先通過判斷,再修改的符號的順序,十分巧妙更輕便的解法 Problem Design an algorithm and write code to serialize and deserialize a binary tree. Writin...
閱讀 2553·2021-11-23 09:51
閱讀 3355·2021-11-22 15:22
閱讀 1868·2021-11-18 13:22
閱讀 2236·2021-09-24 09:48
閱讀 1308·2019-08-29 13:58
閱讀 1297·2019-08-26 13:39
閱讀 2445·2019-08-26 10:48
閱讀 3031·2019-08-26 10:21