LeetCode 990 Satisfiability of Equality Equations (并查集 推荐)

244 篇文章 0 订阅
20 篇文章 1 订阅

You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.

Example 1:

Input: equations = ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.

Example 2:

Input: equations = ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

Constraints:

  • 1 <= equations.length <= 500
  • equations[i].length == 4
  • equations[i][0] is a lowercase letter.
  • equations[i][1] is either '=' or '!'.
  • equations[i][2] is '='.
  • equations[i][3] is a lowercase letter.

题目链接:https://leetcode.com/problems/satisfiability-of-equality-equations/

题目大意:给若然形如x==y或x!=y的式子,问是否存在冲突

题目分析:并查集,相等的先合并,不等的看是否在同一集合即可

2ms,时间击败66.83%

class Solution {
    
    class UFSet {
        int n;
        int[] fa;
        UFSet(int n) {
            this.n = n;
            this.fa = new int[n + 1];
            for (int i = 0; i <= n; i++) {
                fa[i] = i;
            }
        }
        
        int find(int x) {
            if (x == fa[x]) {
                return x;
            }
            fa[x] = find(fa[x]);
            return fa[x];
        }
        
        void union(int a, int b) {
            int r1 = find(a);
            int r2 = find(b);
            if (r1 != r2) {
                fa[r1] = r2;
            }
        }
    }
    
    public boolean equationsPossible(String[] equations) {
        UFSet ufs = new UFSet(26);
        for (String s : equations) {
            int x = s.charAt(0) - 'a';
            int y = s.charAt(3) - 'a';
            if (s.charAt(1) == '=') {
                ufs.union(x, y);
            }
        }
        for (String s : equations) {
            if (s.charAt(1) == '!') {
                int x = s.charAt(0) - 'a';
                int y = s.charAt(3) - 'a';
                if (ufs.find(x) == ufs.find(y)) {
                    return false;
                }
            }
        }
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值