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: region1 and region2, return 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 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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值