力扣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 --;
        }
    }
}
相关推荐
强子感冒了6 分钟前
Java网络编程学习笔记,从网络编程三要素到TCP/UDP协议
java·网络·学习
二哈喇子!8 分钟前
SpringBoot项目右上角选择ProjectNameApplication的配置
java·spring boot
Sarvartha24 分钟前
C++ STL 栈的便捷使用
c++·算法
sin220124 分钟前
MyBatis的执行流程
java·开发语言·mybatis
二哈喇子!29 分钟前
基于Spring Boot框架的车库停车管理系统的设计与实现
java·spring boot·后端·计算机毕业设计
二哈喇子!30 分钟前
基于Spring Boot框架的网络游戏虚拟交易平台的设计与实现
java·springboot·毕设项目
二哈喇子!36 分钟前
JAVA环境变量配置步骤及测试(JDK的下载 & 安装 & 环境配置教程)
java·开发语言
二哈喇子!1 小时前
Java框架精品项目【用于个人学习】
java·spring boot·学习
夏鹏今天学习了吗1 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
二哈喇子!1 小时前
基于SpringBoot框架的网上购书系统的设计与实现
java·大数据·spring boot