LeetCode_684. 冗余连接(并查集)

在这里插入图片描述

如果不懂并查集概念的可以查看之前写过的并查集零基础介绍

思路

  1. 判断两个节点时候是连通的,如果连通则将它们合并到一个集合(树)中。
  2. 如果在判断过程中,发现在并查集中这两个节点已经是连通的了,说明此时这个连通条件是冗余的,即可以被删除的边,将这个集合返回即可
	for (int i = 0; i < edges.length; i++) {
           if (uf.isConnected(edges[i][0], edges[i][1])) {
               return edges[i];
           } else {
               uf.meger(edges[i][0], edges[i][1]);
           }
   	}

代码实现(java)

class Solution {
    class UnionFind {
        private Map<Integer, Integer> father;
        private int numOfSets = 0;

        public UnionFind() {
            father = new HashMap<>();
            numOfSets = 0;
        }

        // 添加方法
        public void add(int x) {
            if (!father.containsKey(x)) {
                father.put(x, null);
                numOfSets++;
            }
        }

        // 寻找父类方法
        public int find(int x) {
            int root = x;
            while (father.get(root) != null) {
                root = father.get(root);
            }
            return root;
        }

        // 合并方法
        public void meger(int x, int y) {
            int rootX = find(x);
            int rootY = find(y);

            if (rootX != rootY) {
                father.put(rootX, rootY);
                numOfSets--;
            }
        }

        // 判断是否相互连接
        public boolean isConnected(int x, int y) {
            return find(x) == find(y);
        }

        // 返回集合数量
        public int getNumOfSets() {
            return numOfSets;
        }
    }
    

    public int[] findRedundantConnection(int[][] edges) {
        UnionFind uf = new UnionFind();

        for (int i = 0; i < edges.length; i++) {
            if (uf.isConnected(edges[i][0], edges[i][1])) {
                return edges[i];
            } else {
                uf.meger(edges[i][0], edges[i][1]);
            }
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值