Day 102: force buckle 721, account merge

Address: leetcode-cn.com/problems/ac…

And check set + deduplicate

class UnionFind { constructor() { this.parent = new Map(); } find(x) {while (this.parent. Has (x)) {x = this.parent. } return x; } // Merge two sets union(p, q) {const rootP = this.find(p); const rootQ = this.find(q); if (rootP ! == rootQ) { this.parent.set(this.find(p), this.find(q)); } } } /** * @param {string[][]} accounts * @return {string[][]} */ var accountsMerge = function (accounts) { let res = new UnionFind(); const map = {}; for (const [...a] of accounts) { for (let i = 1; i < a.length; i++) { map[a[i]] = a[0]; if (i < a.length - 1) { res.union(a[i], a[i + 1]) } } } const sets = {}; // key: string; value: string[] for (const email in map) { const root = res.find(email); if (! sets[root]) { sets[root] = []; } sets[root].push(email); } const ans = []; for (const root in sets) { sets[root].sort(); ans.push([map[root], ...sets[root]]); } return ans };Copy the code

Execution time: 740 ms, beating 35.71% of all JavaScript commits

Memory consumption: 48.8 MB, beating 44.44% of all JavaScript commits