日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Leedcode][JAVA][第990题][等式方程的可满足性][并查集]

發(fā)布時間:2023/12/10 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Leedcode][JAVA][第990题][等式方程的可满足性][并查集] 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

【問題描述】[中等]

給定一個由表示變量之間關(guān)系的字符串方程組成的數(shù)組,每個字符串方程 equations[i] 的長度為 4,并采用兩種不同的形式之一:"a==b" 或 "a!=b"。在這里,a 和 b 是小寫字母(不一定不同),表示單字母變量名。只有當(dāng)可以將整數(shù)分配給變量名,以便滿足所有給定的方程時才返回 true,否則返回 false。

【解答思路】

并查集

時間復(fù)雜度:O(N^2) 空間復(fù)雜度:O(1)

public class Solution {public boolean equationsPossible(String[] equations) {UnionFind unionFind = new UnionFind(26);for (String equation : equations) {char[] charArray = equation.toCharArray();if (charArray[1] == '=') {int index1 = charArray[0] - 'a';int index2 = charArray[3] - 'a';unionFind.union(index1, index2);}}for (String equation : equations) {char[] charArray = equation.toCharArray();if (charArray[1] == '!') {int index1 = charArray[0] - 'a';int index2 = charArray[3] - 'a';if (unionFind.isConnected(index1, index2)) {// 如果合并失敗,表示等式有矛盾,根據(jù)題意,返回 falsereturn false;}}}// 如果檢查了所有不等式,都沒有發(fā)現(xiàn)矛盾,返回 truereturn true;}private class UnionFind {private int[] parent;public UnionFind(int n) {parent = new int[n];for (int i = 0; i < n; i++) {parent[i] = i;}}public int find(int x) {while (x != parent[x]) {parent[x] = parent[parent[x]];x = parent[x];}return x;}/*** @param x* @param y* @return 如果合并成功,返回 true*/public void union(int x, int y) {int rootX = find(x);int rootY = find(y);parent[rootX] = rootY;}public boolean isConnected(int x, int y) {return find(x) == find(y);}}public static void main(String[] args) {// String[] equations = new String[]{"b==a", "a==b"};// String[] equations = new String[]{"a==b","b==c","a==c"};// String[] equations = new String[]{"a==b","b!=c","c==a"};String[] equations = new String[]{"c==c", "b==d", "x!=z"};Solution solution = new Solution();boolean res = solution.equationsPossible(equations);System.out.println(res);} }

【總結(jié)】

1.并查集知識小結(jié)

面試較少出現(xiàn) 酌情掌握




2.并查集時間復(fù)雜度分析


時間復(fù)雜度知乎鏈接:https://www.zhihu.com/question/35090745

3.并查集練習(xí)題


轉(zhuǎn)載鏈接:https://leetcode-cn.com/problems/satisfiability-of-equality-equations/solution/shi-yong-bing-cha-ji-chu-li-bu-xiang-jiao-ji-he-we/

總結(jié)

以上是生活随笔為你收集整理的[Leedcode][JAVA][第990题][等式方程的可满足性][并查集]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。