zoukankan      html  css  js  c++  java
  • LeetCode 1257. Smallest Common Region

    原题链接在这里:https://leetcode.com/problems/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. Also by definition a region X contains itself.

    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.

    题解:

    With the regions list, we could construct partent HashMap with child pointing to parent.

    Maintain all the regions used while finding ancestor of region1.

    When finding ancestor of region2, return the first occurance of region that is in used, it would be smallest common region.

    Time Complexity: O(n). n = regions.size() * average length. h is height of parent tree.

    Space: O(n).

    AC java:

     1 class Solution {
     2     public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
     3         HashMap<String, String> hm = new HashMap<>();
     4         for(List<String> item : regions){
     5             String parent = item.get(0);
     6             for(int i = 1; i<item.size(); i++){
     7                 hm.put(item.get(i), parent);
     8             }
     9         }
    10         
    11         HashSet<String> used = new HashSet<>();
    12         while(region1 != null){
    13             used.add(region1);
    14             region1 = hm.get(region1);
    15         }
    16         
    17         while(!used.contains(region2)){
    18             region2 = hm.get(region2);
    19         }
    20         
    21         return region2;
    22     }
    23 }

    类似Lowest Common Ancestor of a Binary Tree.

  • 相关阅读:
    《计算机图形学-基于3D图形开发技术》读书笔记
    【转】OpenGL和D3D 矩阵对比
    【转】D3D中详细拾取操作
    根据点坐标改变字体显示位置
    静态常量和常量在类中的初始化
    MFC单文档中使用D3D9
    单文档切换OpenGL视图
    超大地形的处理 (Terrain Visualization)【转自知乎】
    又出现这种问题。。。
    属性
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12075993.html
Copyright © 2011-2022 走看看