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
and region2
, return 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 is 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"
思路:核心思想就是LCA,build map是HashMap<String, String> hashmap; 注意map的构造是i + 1 -> 0; 全部指向0;然后用hashset去收集path1,如果path2有遇见path1上面的值,就是LCA;
class Solution {
public String findSmallestRegion(List<List<String>> regions, String region1, String region2) {
// LCA;
HashMap<String, String> graph = new HashMap<>();
for(List<String> region: regions) {
for(int i = 1; i < region.size(); i++) {
graph.put(region.get(i), region.get(0));
}
}
HashSet<String> path1 = new HashSet<>();
while(region1 != null) {
path1.add(region1);
region1 = graph.get(region1);
}
while(!path1.contains(region2)) {
region2 = graph.get(region2);
}
return region2;
}
}