LeetCode Brush Questions 1436. Travel Terminal

LeetCode Brush Questions 1436. Travel Terminal

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    give you a tour circuit diagram, the circuit diagram of an array of travel routes paths, where paths[i] = [cityAi, cityBi]representation from the line will cityAigo directly cityBi. Please find out the destination of this trip, that is, a city that does not have any routes to other cities.
    The title data guarantees that the route map will form a route without loops, so there will only be one travel terminal.
  • Example :
示例 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"
  • Tips :
    • 1 <= paths.length <= 100
    • paths[i].length == 2
    • 1 <= cityAi.length, cityBi.length <= 10
    • cityAi != cityBi
    • All strings are composed of uppercase and lowercase English letters and space characters.
  • Code 1:
class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
        cityAi = []
        cityBi = []
        for i in range(len(paths)):
            cityAi.append(paths[i][0])
            cityBi.append(paths[i][1])
        for i in range(len(paths)):
            if cityBi[i] not in cityAi:
                return cityBi[i]
# 执行用时 :36 ms, 在所有 Python3 提交中击败了94.14%的用户
# 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了100.00%的用户
  • Algorithm description:
    Find the starting point and the end point respectively, and judge whether the end point appears in the starting point, if not, return to the end point.
  • Code 2:
class Solution(object):
    def destCity(self, paths: List[List[str]]) -> str:
        citys = set()
        cityBi = set()
        for path in paths:
            citys.add(path[0])
            citys.add(path[1])
            cityBi.add(path[0])
        return (citys - cityBi).pop()
# 执行用时 :40 ms, 在所有 Python3 提交中击败了82.03%的用户
# 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了100.00%的用户
  • Algorithm description:
    Using the set nature, subtract the set of starting point cities from the set of all cities, and the remaining cities are the ending cities.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106651090