zoukankan      html  css  js  c++  java
  • 【leetcode】1257. Smallest Common Region

    题目如下:

    You are given some lists of regions where the first region of each list includes all other regions in that list.

    Naturally, if a region X contains another region Y then X is bigger than Y.

    Given two regions region1region2, find out the smallest region that contains both of them.

    If you are given regions r1r2 and r3 such that r1 includes r3, it is guaranteed there is no r2 such that r2 includes r3.


    It's guaranteed the smallest region exists.

    Example 1:

    Input:
    regions = [["Earth","North America","South America"],
    ["North America","United States","Canada"],
    ["United States","New York","Boston"],
    ["Canada","Ontario","Quebec"],
    ["South America","Brazil"]],
    region1 = "Quebec",
    region2 = "New York"
    Output: "North America"

    Constraints:

    • 2 <= regions.length <= 10^4
    • region1 != region2
    • All strings consist of English letters and spaces with at most 20 letters.

    解题思路:首先递归找出region1所属的regions链,并保持结果;然后再递归查找region2所属的regions链,找到第一个region在region1所属的regions链即可。

    代码如下:

    class Solution(object):
        def findSmallestRegion(self, regions, region1, region2):
            """
            :type regions: List[List[str]]
            :type region1: str
            :type region2: str
            :rtype: str
            """
            dic = {}
            for region in regions:
                parent = region[0]
                for i in range(1,len(region)):
                    dic[region[i]] = parent
    
            dic_region1 = {}
            while region1 in dic:
                dic_region1[region1] = 1
                region1 = dic[region1]
    
            while region2 in dic:
                if region2 in dic_region1:
                    return region2
                region2 = dic[region2]
            return regions[0][0]
  • 相关阅读:
    反射式光电开关QRE1113
    labview程序性能优化
    labview中小黑点,小红点
    简述时钟周期、机器周期、指令周期的概念及三者之间的关系
    C++中的#和##运算符
    NTC与PTC压敏电阻在电源电路中起的作用
    常用DC-DC;AC-DC电源芯片
    PC817与TL431的配合电路探讨
    React入门
    WebRTC网关服务器单端口方案实现
  • 原文地址:https://www.cnblogs.com/seyjs/p/11878841.html
Copyright © 2011-2022 走看看