并查集:LeetCode:990. 等式方程的可满足性

题目链接:LeetCode 990
题目思路:并查集,第一次遍历构建并查集的集合关系,第二次检查违反并查集集合关系的情况,如果有就返回false,如果没有的话返回true即可。

class Solution {
    public boolean equationsPossible(String[] equations) {
        // 初始化字母序列的并查集
        int[] father = new int[26];
        for(int i = 0; i < 26; i++)
        {
            father[i] = i;
        }
        // 构建并查集的关系
        for(String str: equations)
        {
            if(str.charAt(1) == '=')
            {
                int index1 = str.charAt(0) - 'a';
                int index2 = str.charAt(3) - 'a';
                union(father, index1, index2);
            }
        }
        // 检查违反并查集的关系
        for(String str: equations)
        {
            if(str.charAt(1) == '!')
            {
                int index1 = str.charAt(0) - 'a';
                int index2 = str.charAt(3) - 'a';
                if(find(father, index1) == find(father, index2))
                    return false;
            }
        }
        return true;
    }

    public void union(int[] father, int i, int j)
    {
        // 这个地方左边记得是将i的父亲指向j的父亲,错好几次了
        father[find(father, i)] = find(father, j);
    }

    public int find(int[] father, int i)
    {
        while(father[i] != i)
        {
            father[i] = find(father, father[i]);
            i = father[i];
        }
        return father[i];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值