力扣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 --;
        }
    }
}
相关推荐
二十雨辰3 分钟前
[学成在线]23-面试题总结
java·后端
神马都会亿点点的毛毛张24 分钟前
【SpringBoot教程】SpringBoot自定义注解与AOP实现切面日志
java·spring boot·后端·spring·spring aop·aspectj
triticale26 分钟前
【数据结构】求有向图强连通分量的方法
数据结构·图论
一只码代码的章鱼34 分钟前
5.4学习记录
学习·算法·动态规划
lally.41 分钟前
java安全入门
java
IT技术员44 分钟前
【Java学习】关于springBoot的自动配置和起步依赖
java·spring boot·学习
forestsea1 小时前
Maven 依赖发布与仓库治理
java·maven
zhangxueyi1 小时前
Java实现归并排序算法
java·数据结构·算法
Bob99981 小时前
基于晶晨S905L3B单网线盒子的Armbian 或openwrt应用
java·javascript·网络·数据结构·c++·python·eclipse
sukalot1 小时前
window 显示驱动开发-线程和同步级别为零级
java·开发语言·驱动开发