本文共 672 字,大约阅读时间需要 2 分钟。
为了找到旅游线路图的终点站,我们需要确定哪个城市没有任何出边连接到其他城市。终点站是所有起点城市之外的那个城市。
步骤如下:
代码实现:
def destCity(paths): # 收集所有起点城市 start_set = {path[0] for path in paths} # 收集所有出现过的城市 all_cities = {city for path in paths for city in path} # 遍历所有城市,找到不在起点集合中的终点城市 for city in all_cities: if city not in start_set: return city # 根据题目,至少有一个终点,所以无需处理无返回的情况 示例测试:
示例1:输入:paths = [["London","New York"], ["New York","Lima"], ["Lima","Sao Paulo"]]输出:"Sao Paulo"
示例2:输入:paths = [["B","C"], ["D","B"], ["C","A"]]输出:"A"
示例3:输入:paths = [["A","Z"]]输出:"Z"
通过这种方法,我们可以准确地找到旅游线路图的终点站。
转载地址:http://dadzz.baihongyu.com/