原题链接在这里: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:

 class Solution {
public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
HashMap<String, String> hm = new HashMap<>();
for(List<String> item : regions){
String parent = item.get(0);
for(int i = 1; i<item.size(); i++){
hm.put(item.get(i), parent);
}
} HashSet<String> used = new HashSet<>();
while(region1 != null){
used.add(region1);
region1 = hm.get(region1);
} while(!used.contains(region2)){
region2 = hm.get(region2);
} return region2;
}
}

类似Lowest Common Ancestor of a Binary Tree.

最新文章

  1. bootstrap快速搭建属于自己的后台模板库
  2. [蓝牙] 3、 剖析BLE心率检测工程
  3. Android之Notification介绍
  4. Android 5.0 如何正确启用isLoggable(一)__使用详解
  5. linux bq20z75 驱动
  6. 类似 select 选择框效果及美化
  7. 【转】Android Listener侦听的N种写法
  8. DKNightVersion的基本使用(夜间模式)
  9. iOS动态运行时方法
  10. uva 10655 - Contemplation! Algebra(矩阵高速幂)
  11. 移动端 常见布局CSS3的细节
  12. Firebug 非常好用
  13. WebGIS前端瓦片地图显示原理及实现
  14. JAVA处理Http请求(GET,POST)
  15. .net core 2.1 Ef 连接Mysql数据库 DB first
  16. Java多线程系列目录
  17. bzoj4001: [TJOI2015]概率论
  18. YOLOv2-darknet 内容解析
  19. 服务端JSON内容中有富文本时
  20. 【BZOJ】1061: [Noi2008]志愿者招募

热门文章

  1. Codeforces Round 589 (Div. 2) 题解
  2. VS Code 提示‘未找到Git。请安装Git,或在“git.path”设置中配置’
  3. php explode容易犯的错误
  4. jQuery源码分析(九) 异步队列模块 Deferred 详解
  5. Chrome 手动安装.crx插件
  6. Kubernetes 静态PV使用
  7. 【06】Nginx:文件下载 / 用户认证
  8. Ubuntu Err:1 http://us.archive.ubuntu.com/ubuntu bionic InRelease Could not resolve &#39;us.archive.ubuntu.com&#39; 错误
  9. WPF toolkit AutoCompleteBox
  10. Vue-cli3脚手架工具快速创建一个项目