LeetCode 题解工作台

旅行终点站

给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityA i , cityB i ] 表示该线路将会从 cityA i 直接前往 cityB i 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市 。 题目数据保证线路图会形成一条不存…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,终点一定不会出现在所有 中,因此,我们可以先遍历一遍 ,将所有 放入一个集合 中,然后再遍历一遍 ,找到不在 中的 即可。 时间复杂度 ,空间复杂度 。其中 为 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一份旅游线路图,该线路图中的旅行线路用数组 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"

 

提示:

  • 1 <= paths.length <= 100
  • paths[i].length == 2
  • 1 <= cityAi.length, cityBi.length <= 10
  • cityA!= cityBi
  • 所有字符串均由大小写英文字母和空格字符组成。
lightbulb

解题思路

方法一:哈希表

根据题目描述,终点一定不会出现在所有 cityA\textit{cityA} 中,因此,我们可以先遍历一遍 paths\textit{paths},将所有 cityA\textit{cityA} 放入一个集合 s\textit{s} 中,然后再遍历一遍 paths\textit{paths},找到不在 s\textit{s} 中的 cityB\textit{cityB} 即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nnpaths\textit{paths} 的长度。

1
2
3
4
5
class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
        s = {a for a, _ in paths}
        return next(b for _, b in paths if b not in s)
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate identifies the key insight: finding the city with no outgoing path.

  • question_mark

    Candidate demonstrates an understanding of hash table or set usage for efficient lookups.

  • question_mark

    Candidate efficiently handles edge cases like single-path graphs or varying city names.

warning

常见陷阱

外企场景
  • error

    Mistaking the first city in the list as the destination without considering all paths.

  • error

    Overcomplicating the solution by using unnecessary data structures.

  • error

    Missing the linear time complexity requirement and attempting inefficient solutions like nested loops.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    The problem can be extended to find multiple destination cities in a more complex graph where multiple disconnected lines of paths exist.

  • arrow_right_alt

    Consider adding a constraint that allows for more than one city to have no outgoing path, turning the problem into a search for all destination cities.

  • arrow_right_alt

    Variant: What if the paths form a loop? How would the solution adapt to handle circular references?

help

常见问题

外企场景

旅行终点站题解:数组·哈希·扫描 | LeetCode #1436 简单