zoukankan      html  css  js  c++  java
  • [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 cityBiReturn 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。然后我们再从任意一个城市出发,看看最后到底终点站是哪个城市。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public String destCity(List<List<String>> paths) {
     3         HashMap<String, String> map = new HashMap<>();
     4         for (List<String> p : paths) {
     5             map.put(p.get(0), p.get(1));
     6         }
     7 
     8         String res = paths.get(0).get(0);
     9         while (map.containsKey(res)) {
    10             res = map.get(res);
    11         }
    12         return res;
    13     }
    14 }

    LeetCode 题目总结

  • 相关阅读:
    【JavaScript数据结构系列】04-优先队列PriorityQueue
    【JavaScript数据结构系列】02-栈Stack
    【JavaScript数据结构系列】01-数组Array
    【JavaScript数据结构系列】00-开篇
    2019个人年度总结
    批处理·命令行中常用的操作
    flutter 环境出错后排查
    [图解算法]线性时间选择Linear Select——<递归与分治策略>
    阿里云轻量应用服务器——配置MySQL远程连接(踩坑,LAMP+CentOS)
    [知识复习] C语言文件读写
  • 原文地址:https://www.cnblogs.com/cnoodle/p/15370322.html
Copyright © 2011-2022 走看看