力扣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 --;
        }
    }
}
相关推荐
code_weic19 小时前
Java AI开发框架 - LangChain4J学习笔记
java·人工智能·ai·langchain
一个不知名程序员www19 小时前
算法学习入门---stack(C++)
c++·算法
wh_cxy19 小时前
Spring 的本地消息
java
米芝鱼19 小时前
Unity自定义按钮
算法·ui·unity·游戏引擎·编辑器扩展
野蛮人6号19 小时前
力扣热题100道,内容和力扣官方稍有不同,记录了本人的一些独特的解法
算法·leetcode
米芝鱼19 小时前
Unity自定义TextImage,鼠标悬浮显示信息
算法·ui·unity·编辑器·游戏引擎·图形渲染
pengzhuofan19 小时前
Java开发中的AI Prompt管理指南
java·开发语言·prompt
wh_cxy19 小时前
Java泛型通配符入门教程
java
乌暮19 小时前
JavaEE初阶--线程的状态
java·java-ee
悟空码字19 小时前
SpringBoot 整合 RabbitMQ:和这只“兔子”交朋友
java·后端·rabbitmq