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 region1
, region2
, find out the smallest region that contains both of them.
If you are given regions r1
, r2
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.
最小公共区域。
给你一些区域列表 regions ,每个列表的第一个区域都包含这个列表内所有其他区域。
很自然地,如果区域 X 包含区域 Y ,那么区域 X 比区域 Y 大。
给定两个区域 region1 和 region2 ,找到同时包含这两个区域的 最小 区域。
如果区域列表中 r1 包含 r2 和 r3 ,那么数据保证 r2 不会包含 r3 。
数据同样保证最小公共区域一定存在。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-common-region
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题跟235,236题很像,找的是两个 region 的最小公共祖先。那么这里我们需要一个hashmap<String, String> 记录每个 region 和他的父节点。同时我们还需要一个 hashset 记录有哪些 region 被访问过。首先我们用 hashmap 记录每个 region 和他的父节点,记录好了之后,对于 region1 ,我们开始执行 DFS,用 hashset 记录好 region1 的每一个父节点,直到无法遍历为止。
此时我们再从 region2 开始做 DFS 遍历去找 region2 的父节点。如果当前找到的这个父节点不存在于 hashset,就接着再往上一层找;如果在 hashset 里找到了 region2 的父节点,说明这个父节点就是 region1 和 region2 的最小公共祖先。
时间O(n^2)
空间O(n)
Java实现
1 class Solution { 2 public String findSmallestRegion(List<List<String>> regions, String region1, String region2) { 3 HashMap<String, String> map = new HashMap<>(); 4 HashSet<String> set = new HashSet<>(); 5 for (List<String> r : regions) { 6 for (int i = 1; i < r.size(); i++) { 7 map.put(r.get(i), r.get(0)); 8 } 9 } 10 11 while (region1 != null) { 12 set.add(region1); 13 region1 = map.get(region1); 14 } 15 while (!set.contains(region2)) { 16 region2 = map.get(region2); 17 } 18 return region2; 19 } 20 }
相关题目
235. Lowest Common Ancestor of a Binary Search Tree
236. Lowest Common Ancestor of a Binary Tree
865. Smallest Subtree with all the Deepest Nodes