684. 冗余连接(并查集)

package com.heu.wsq.leetcode.graph;

/**
 * 684. 冗余连接
 * @author wsq
 * @date 2021/1/13
 * 在本问题中, 树指的是一个连通且无环的无向图。
 * 输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
 * 结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
 * 返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。
 *
 * 示例 1:
 * 输入: [[1,2], [1,3], [2,3]]
 * 输出: [2,3]
 * 解释: 给定的无向图为:
 *   1
 *  / \
 * 2 - 3
 *
 * 链接:https://leetcode-cn.com/problems/redundant-connection
 */
public class FindRedundantConnection {
    public int[] findRedundantConnection(int[][] edges){
        int n = edges.length;
        UnionFind unionFind = new UnionFind(n);
        for (int i = 0; i < n; i++){
            int[] edge = edges[i];
            if (unionFind.isConnected(edge[0], edge[1])){
                return edge;
            }
            unionFind.union(edge[0], edge[1]);
        }
        return new int[0];
    }
    private class UnionFind{
        private int[] parent;
        private int[] rank;

        public UnionFind(int n){
            this.parent = new int[n];
            this.rank = new int[n];
            // 初始化数组内容
            for(int i = 0; i < n; i++){
                this.parent[i] = i;
                this.rank[i] = 1;
            }
        }

        public void union(int x, int y){
            x = x - 1;
            y = y - 1;
            int rootX = find(x);
            int rootY = find(y);
            if (rootX == rootY){
                return;
            }
            if (this.rank[rootX] == this.rank[rootY]){
                this.parent[rootX] = rootY;
                this.rank[rootY] += 1;
            }else if (this.rank[rootX] > this.rank[rootY]){
                this.parent[rootY] = rootX;
            }else{
                this.parent[rootX] = rootY;
            }
        }

        public int find(int x){
            x -= 1;
            int r = x;
            while (r != this.parent[r]){
                r = this.parent[r];
            }
            int k = x;
            while (k != r){
                int tmp = this.parent[k];
                this.parent[k] = r;
                k = tmp;
            }
            return r;
        }

        public boolean isConnected(int x, int y){
            x -= 1;
            y -= 1;
            int rootX = find(x);
            int rootY = find(y);
            return rootX == rootY;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值