题目是LeetCode第187场周赛的第一题,链接:旅行终点站。具体描述为:给你一份旅游线路图,该线路图中的旅行线路用数组paths
表示,其中paths[i] = [cityAi, cityBi]
表示该线路将会从cityAi
直接前往cityBi
。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。
示例1:
输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
输出:"Sao Paulo"
解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> "Lima" -> "Sao Paulo" 。
示例2:
输入:paths = [["B","C"],["D","B"],["C","A"]]
输出:"A"
解释:所有可能的线路是:
"D" -> "B" -> "C" -> "A".
"B" -> "C" -> "A".
"C" -> "A".
"A".
显然,旅行终点站是 "A" 。
示例3:
输入:paths = [["A","Z"]]
输出:"Z"
题目很简单,直接用map来保存路线信息,即{出发->到达}
,然后随便从一个地点出发,通过map.get(出发)
得到下一个出发点,一直到下一个出发点不在map中说明到了终点。时间复杂度为
O
(
n
)
O(n)
O(n),空间复杂度为
O
(
n
)
O(n)
O(n)。
JAVA版代码如下:
class Solution {
public String destCity(List<List<String>> paths) {
Map<String, String> map = new HashMap<>();
for (List<String> path : paths) {
map.put(path.get(0), path.get(1));
}
String result = paths.get(0).get(0);
while (map.containsKey(result)) {
result = map.get(result);
}
return result;
}
}
提交结果如下:
![](https://img-blog.csdnimg.cn/2020050617152185.png)
Python版代码如下:
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
start2end = {}
for path in paths:
start2end[path[0]] = path[1]
start = paths[0][0]
while start in start2end:
start = start2end[start]
return start
提交结果如下:
![](https://img-blog.csdnimg.cn/20200506171937634.png)