leetcode 990 等式方程 (6-8刷题)

方法:并查集。

思路:相等的关系可以传递,最终的结果集必然是若干个集合,每个集合里的变量拥有相同的值,即处在同一个连通分量里。而不等关系则是两个变量在不同的连通分量里。
所以,先针对相等关系建立并查集,而后判断每个不等关系是否都满足即可。
代码:

class Solution {
    // 并查集,这里并查集的根节点与下标相等。
    public int[] parent=new int[26];
    public int findParent(int t){
        while(parent[t]!=t){
            t=parent[t];
        }
        return t;
    }
    public void union(int a,int b){
        int pa=findParent(a),pb=findParent(b);
        if(pa==pb)return;
        parent[pb]=pa;
    }
    public boolean equationsPossible(String[] equations) {
        // 并查集初始化。
        for(int i=0;i<parent.length;i++){
            parent[i]=i;
        }
        for(int i=0;i<equations.length;i++){
            if(equations[i].charAt(1)=='='){
              union(equations[i].charAt(0)-'a',equations[i].charAt(3)-'a');
            }
        }
        for(int i=0;i<equations.length;i++){
            if(equations[i].charAt(1)=='!'){
                if(findParent(equations[i].charAt(0)-'a')==findParent(equations[i].charAt(3)-'a')){
                    return false;
                }
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fuckguidao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值