Redundant Connection (684)

此题是明显的Union Find的问题。

和Mini Spining tree相似, 如果加入的新边使得原有的数据形成了环(就是union的结果是有相同的父亲)。说明这个边不应该加入

 

首先还是套路写一个Union Find的class

class UnionFind{
    Map<Integer, Integer> father;
    
    public UnionFind(int n){
        father = new HashMap<>();
        for(int i = 1 ; i <= n ; ++i){
            father.put(i,i);
        }
    }
    
    public void union(int a, int b){
        int father_a = find(a) ;
        int father_b = find(b) ;
        if(father_a != father_b){
            father.put(father_a, father_b);
        }
    }
    private int find(int a){
        int father_a = father.get(a);
        if(father_a!= a){
            father_a = find(father_a);
        }
        father.put(a, father_a);
        return father_a;
    }
    public boolean isValid(int a, int b){
        return find(a) != find(b);
    }
}

 

 

主函数调用

    public int[] findRedundantConnection(int[][] edges) {
        if(edges.length == 0) return new int[0];
        
        UnionFind uf = new UnionFind(edges.length);
        
        for(int i = 0 ; i < edges.length; ++i){
            int a = edges[i][0];
            int b = edges[i][1];
            if(uf.isValid(a, b)){
                uf.union(a,b);
            }else{
                return edges[i];
            }
        }
        return new int[0];
    }
}

 

转载于:https://www.cnblogs.com/HUTONG749/p/9597424.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值