力扣labuladong——一刷day81

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • [一、力扣990. 等式方程的可满足性](#一、力扣990. 等式方程的可满足性)

前言


并查集(Union-Find)算法是一个专门针对「动态连通性」的算法,我之前写过两次,因为这个算法的考察频率高,而且它也是最小生成树算法的前置知识,所以我整合了本文,争取一篇文章把这个算法讲明白

一、力扣990. 等式方程的可满足性

java 复制代码
class Solution {
    public boolean equationsPossible(String[] equations) {
        if(equations == null || equations.length == 0){
            return true;
        }
        int n = equations.length;
        Uf uf = new Uf(27);
        for(int i = 0; i < n; i ++){
            char c1 = equations[i].charAt(1);
            if(c1 == '='){
                int x = equations[i].charAt(0) - 'a';
                int y = equations[i].charAt(3) - 'a';
                uf.union(x,y);
            }
        }
        for(int i = 0; i < n; i ++){
            if(equations[i].charAt(1) == '!'){
                int x = equations[i].charAt(0) - 'a';
                int y = equations[i].charAt(3) - 'a';
                if(uf.getConnection(x, y)){
                    return false;
                }
            }
        }
        return true;
    }
    class Uf{
        private int count;
        private int[] parent;
        public Uf(int n){
            this.count = n;
            this.parent = new int[n];
            for(int i = 0; i < n; i ++){
                parent[i] = i;
            }
        }
        public int getCount(){
            return count;
        }
        public int find(int x){
            if(parent[x] != x){
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }
        public boolean getConnection(int x, int y){
            int rootx = find(x);
            int rooty = find(y);
            return rootx == rooty;
        }
        public void union(int x, int  y){
            int rootx = find(x);
            int rooty = find(y);
            if(rootx == rooty){
                return;
            }
            this.parent[rootx] = rooty;
            count --;
        }
    }
}
相关推荐
会飞的小蛮猪10 小时前
SkyWalking运维之路(Java探针接入)
java·运维·经验分享·容器·skywalking
通域10 小时前
解决启动IDEA后CPU 及内存占用过高配置调整
java·ide·intellij-idea
papership10 小时前
【入门级-算法-5、数值处理算法:高精度的乘法】
数据结构·算法
earthzhang202110 小时前
【1039】判断数正负
开发语言·数据结构·c++·算法·青少年编程
谈笑也风生10 小时前
只出现一次的数字 II(一)
数据结构·算法·leetcode
蕓晨10 小时前
auto 自动类型推导以及注意事项
开发语言·c++·算法
一袋米扛几楼9810 小时前
【软件安全】C语言特性 (C Language Characteristics)
java·c语言·安全
mjhcsp11 小时前
C++ 递推与递归:两种算法思想的深度解析与实战
开发语言·c++·算法
_OP_CHEN11 小时前
算法基础篇:(三)基础算法之枚举:暴力美学的艺术,从穷举到高效优化
c++·算法·枚举·算法竞赛·acm竞赛·二进制枚举·普通枚举
m0_7482480211 小时前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
java·开发语言·c++·算法