Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 0119d0c

Browse files
committed
Add solution #332
1 parent f6fbf31 commit 0119d0c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

0332-reconstruct-itinerary.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 332. Reconstruct Itinerary
3+
* https://leetcode.com/problems/reconstruct-itinerary/
4+
* Difficulty: Hard
5+
*
6+
* You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure
7+
* and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
8+
*
9+
* All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with
10+
* "JFK". If there are multiple valid itineraries, you should return the itinerary that has the
11+
* smallest lexical order when read as a single string.
12+
*
13+
* For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
14+
*
15+
* You may assume all tickets form at least one valid itinerary. You must use all the tickets once
16+
* and only once.
17+
*/
18+
19+
/**
20+
* @param {string[][]} tickets
21+
* @return {string[]}
22+
*/
23+
var findItinerary = function(tickets) {
24+
const graph = new Map();
25+
const itinerary = [];
26+
27+
for (const [from, to] of tickets) {
28+
if (!graph.has(from)) {
29+
graph.set(from, []);
30+
}
31+
graph.get(from).push(to);
32+
}
33+
34+
for (const [_, destinations] of graph) {
35+
destinations.sort().reverse();
36+
}
37+
38+
dfs('JFK');
39+
40+
return itinerary.reverse();
41+
42+
function dfs(airport) {
43+
while (graph.has(airport) && graph.get(airport).length) {
44+
dfs(graph.get(airport).pop());
45+
}
46+
itinerary.push(airport);
47+
}
48+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@
268268
329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard|
269269
330|[Patching Array](./0330-patching-array.js)|Hard|
270270
331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium|
271+
332|[Reconstruct Itinerary](./0332-reconstruct-itinerary.js)|Hard|
271272
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|
272273
337|[House Robber III](./0337-house-robber-iii.js)|Medium|
273274
338|[Counting Bits](./0338-counting-bits.js)|Easy|

0 commit comments

Comments
 (0)