Java-数据结构-并查集<二>

本文详细介绍了Java中的并查集数据结构,包括其简单介绍、主要构成和实现方式,以及HashMap和数组模板。并通过LeetCode上的多个题目(如547,684,1905等)进行实战解析,展示并查集在解决实际问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.并查集的简单介绍

二. 并查集的主要构成和实现方式

三.HashMap模板和数组模板

由于在下文的模板基本一致,不再每次都罗列,大体的模板如下,若有错误可以在leetcode找到对应的题目解答,已经附上连接。

HashMap


class UnionFind {
    private Map<Integer,Integer> father;
    
    public UnionFind() {
        father = new HashMap<Integer,Integer>();
    }
    
    public void add(int x) {
        if (!father.containsKey(x)) {
            father.put(x, null);
        }
    }
    
    public void merge(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        
        if (rootX != rootY){
            father.put(rootX,rootY);
        }
    }
    
    public int find(int x) {
        int root = x;
        
        while(father.get(root) != null){
            root = father.get(root);
        }
        
        while(x != root){
            int original_father = father.get(x);
            father.put(x,root);
            x = original_father;
        }
        
        return root;
    }
    
    public boolean isConnected(int x, int y) {
        return find(x) == find(y);
    }
}

数组

class UnionFind{
    public int[] parent;
    public int count;
    //初始化
    public UnionFind(int n){
        parent = new int[n];
        count = n;
        for(int i = 0; i< n; i++){
            parent[i] = i;
        }
    }
    //查找
    public int find(int x){
        while(x != parent[x]){
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
    //合并节点
    public void union(int x, int y){
        if(find(x) == find(y)) return;
        parent[find(x)] = find(y);
        count--;
    }
    //是否为同一父节点,也就是是否联通
    public boolean isConnected(int x, int y){
        return find(x) == find(y);
    }
    //返回数量
    public int getCount(){
        return count;
    }
}

三. leetcode实战

1. leetcode547 省份数量

2. leetcode684 冗余连接

以上未出现部分圈全在在前篇文章,不再赘述

Java-数据结构-并查集<一>

3. leetcode1905 统计子岛屿

给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值