[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。然后我们再从任意一个城市出发,以这个城市当做 key,走到 value,然后再以 value 当做下一个 key,继续走到 value,直到走到一个没有 value 的城市,这个城市就是终点站。
复杂度
时间O(n)
空间O(n)
Java实现一
Java实现
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;
}
}
Java实现二
Java实现
// 把所有的起点加入hashset,找唯一不在hashset里的点
class Solution {
public String destCity(List<List<String>> paths) {
Set<String> set = new HashSet<>();
for (List<String> path : paths) {
String from = path.get(0);
set.add(from);
}
for (List<String> path : paths) {
String to = path.get(1);
if (!set.contains(to)) {
return to;
}
}
return "";
}
}