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. 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"

 分析:

我们首先创建树,这个树是从child -> parent mapping, 然后把这个把region1所有的ancestor放在一个set里面,最后从region2最底层出发,看是否有parent存在于 region1 的ancestor set里面,如果有的话,那么那个node明显就是smallest common region.

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

ref: https://leetcode.com/problems/smallest-common-region/discuss/430500/JavaPython-3-Lowest-common-ancestor-w-brief-explanation-and-analysis.

posted @ 2020-12-27 00:54  北叶青藤  阅读(118)  评论(0)    收藏  举报