力扣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 --;
        }
    }
}
相关推荐
甜鲸鱼18 小时前
【Spring Boot + OpenAPI 3】开箱即用的 API 文档方案(SpringDoc + Knife4j)
java·spring boot·后端
robch18 小时前
Java后端优雅的实现分页搜索排序-架构2
java·开发语言·架构
她说..18 小时前
在定义Java接口参数时,遇到整数类型,到底该用int还是Integer?
java·开发语言·java-ee·springboot
两广总督是码农18 小时前
IDEA-SpringBoot热部署
java·spring boot·intellij-idea
程序员-King.18 小时前
day110—同向双指针(数组)—最多K个重复元素的最长子数组(LeetCode-2958)
算法·leetcode·双指针
傻小胖18 小时前
第3讲:BTC-数据结构-北大肖臻老师客堂笔记
数据结构
MoFe118 小时前
【.net/.net core】【报错处理】另一个 SqlParameterCollection 中已包含 SqlParameter。
java·.net·.netcore
sang_xb18 小时前
深入解析 HashMap:从存储架构到性能优化
android·java·性能优化·架构
做怪小疯子18 小时前
LeetCode 热题 100——二叉树——二叉树的右视图
算法·leetcode·职场和发展
Swift社区18 小时前
LeetCode 442 - 数组中重复的数据
算法·leetcode·职场和发展