力扣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 小时前
(LeetCode-Hot100)253. 会议室 II
java·算法·leetcode·go
Jason_Honey23 小时前
【平安Agent算法岗面试-二面】
人工智能·算法·面试
程序员酥皮蛋3 小时前
hot 100 第三十五题 35.二叉树的中序遍历
数据结构·算法·leetcode
追随者永远是胜利者3 小时前
(LeetCode-Hot100)207. 课程表
java·算法·leetcode·go
香芋Yu4 小时前
【大模型面试突击】08_推理范式与思维链
面试·职场和发展
仰泳的熊猫4 小时前
题目1535:蓝桥杯算法提高VIP-最小乘积(提高型)
数据结构·c++·算法·蓝桥杯
那起舞的日子5 小时前
动态规划-Dynamic Programing-DP
算法·动态规划
yanghuashuiyue5 小时前
lambda+sealed+record
java·开发语言
闻缺陷则喜何志丹5 小时前
【前后缀分解】P9255 [PA 2022] Podwyżki|普及+
数据结构·c++·算法·前后缀分解
每天吃饭的羊5 小时前
时间复杂度
数据结构·算法·排序算法