[LeetCode] 1436. Destination City

You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.

It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

Example 1:
Input: paths = [[“London”,”New York”],[“New York”,”Lima”],[“Lima”,”Sao Paulo”]]
Output: “Sao Paulo”
Explanation: Starting at “London” city you will reach “Sao Paulo” city which is the destination city. Your trip consist of: “London” -> “New York” -> “Lima” -> “Sao Paulo”.

Example 2:
Input: paths = [[“B”,”C”],[“D”,”B”],[“C”,”A”]]
Output: “A”
Explanation: All possible trips are:
“D” -> “B” -> “C” -> “A”.
“B” -> “C” -> “A”.
“C” -> “A”.
“A”.
Clearly the destination city is “A”.

Example 3:
Input: paths = [[“A”,”Z”]]
Output: “Z”

Constraints:
1 <= paths.length <= 100
paths[i].length == 2
1 <= cityAi.length, cityBi.length <= 10
cityAi != cityBi
All strings consist of lowercase and uppercase English letters and the space character.

旅行终点站。

给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。
题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行终点站。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/destination-city
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是哈希表。这里我们用一个哈希表把所有的 path 存下来,存的方式是hashmap<key, value> = cityA, cityB。然后我们再从任意一个城市出发,看看最后到底终点站是哪个城市。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public String destCity(List<List<String>> paths) {
HashMap<String, String> map = new HashMap<>();
for (List<String> path : paths) {
String from = path.get(0);
String to = path.get(1);
map.put(from, to);
}

String city = paths.get(0).get(0);
while (map.containsKey(city)) {
city = map.get(city);
}
return city;
}
}

[LeetCode] 1436. Destination City
https://shurui91.github.io/posts/803566732.html
Author
Aaron Liu
Posted on
October 6, 2021
Licensed under