旅行终点站
难度:
标签:
题目描述
代码结果
运行时间: 18 ms, 内存: 16.1 MB
/*
* Problem: Given a list of paths where each path represents a direct trip from city A to city B,
* the goal is to find the final destination city which has no outgoing paths.
* Approach: Use Java Streams to process the list of paths, extract destination cities, and filter out starting cities.
*/
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class DestinationCityStream {
public String destCity(List<List<String>> paths) {
// Create a set of destination cities using streams
Set<String> destinationSet = paths.stream()
.map(path -> path.get(1))
.collect(Collectors.toSet());
// Remove all cities that are starting points of any path
paths.stream()
.map(path -> path.get(0))
.forEach(destinationSet::remove);
// The remaining city is the final destination
return destinationSet.iterator().next();
}
}
解释
方法:
题解的思路是通过使用两个集合来区分起始城市和目的地城市。对于每一条路径,将起点城市添加到起始集合,将终点城市添加到终点集合。由于每个城市只有一条出发路线,终点站将不会出现在起始集合中。因此,通过计算终点集合与起始集合的差集,即可得到终点站。由于题目保证了路径的连续性且无环,这个差集中将只有一个元素,即为我们需要的终点站。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
在题解中使用集合来区分起始城市和目的地城市的方法是否能有效处理所有情况,例如连续多个路径有相同的起始或终点城市的情况?
▷🦆
为什么题解中选择使用集合而不是列表或字典来存储起点和终点城市,集合在这里有什么特别的优势?
▷🦆
题解中提到的计算两个集合的差集的过程中,如果存在多个城市不在起始集合中会怎样处理?
▷🦆
在实际的Python代码实现中,`list(finish_set - start_set)[0]`这一行是否有潜在的风险,例如当差集为空时会发生什么?
▷