Re: [閒聊] 每日LeetCode

看板Marginalman作者 (みけねこ的鼻屎)時間1年前 (2022/09/27 23:48), 1年前編輯推噓2(203)
留言5則, 2人參與, 1年前最新討論串13/719 (看更多)
※ 引述《pandix (麵包屌)》之銘言: : 990. Satisfiability of Equality Equations 這題我今天上班的時候有解 看到的時候沒想到可以用併查集來解 而且我併查集忘光光了還複習了一下實現方法 一開始是想用無向圖 我參考你的概念然後做一點點改良: 1.不排序整個陣列,遍歷兩次陣列,第一次遍歷 == 的 第二次遍歷 != 的 2.時間複雜度比排序好一些,排序複雜度 O(nlogn) 遍歷兩次複雜度 O(2n) Java Code: class Solution { public boolean equationsPossible(String[] equations) { int[] root = new int[26]; for(int i = 0; i < 26; i++) root[i] = i; for(String eq : equations) { if(eq.charAt(1) == '!') continue;; int a = eq.charAt(0), b = eq.charAt(3); root[find(root, a - 'a')] = find(root, b - 'a'); } for(String eq : equations) { if(eq.charAt(1) == '=') continue;; int a = eq.charAt(0), b = eq.charAt(3); if(root[find(root, a - 'a')] == find(root, b - 'a')) return false; } return true; } private int find(int[] root, int x) { return root[x] == x ? x : find(root, root[x]); } } -- https://i.imgur.com/YPBHGGE.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 115.165.253.177 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1664293704.A.76D.html ※ 編輯: Rushia (115.165.253.177 臺灣), 09/27/2022 23:51:47

09/27 23:58, 1年前 , 1F
對耶 好像不用特地sort
09/27 23:58, 1F

09/28 00:03, 1年前 , 2F
你的find 可以寫成 root[x] = (root[x] == x ? x : ...);
09/28 00:03, 2F

09/28 00:03, 1年前 , 3F
這樣可以邊找邊把樹攤平
09/28 00:03, 3F

09/28 00:03, 1年前 , 4F
我知道ㄚ 只是有點懶
09/28 00:03, 4F

09/28 00:04, 1年前 , 5F
這樣會多一行 ˋˊ
09/28 00:04, 5F
幹不對可以一行欸 return root[x] == x ? x : (root[x] = find(root, root[x])); 我好爛 我之前都這樣寫 if(root[x] == x) return x; return root[x] = find(root, root[x]); ※ 編輯: Rushia (115.165.253.177 臺灣), 09/28/2022 00:07:33
文章代碼(AID): #1ZCnj8Tj (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZCnj8Tj (Marginalman)