第一百零二天:力扣 721题,账户合并
地址:leetcode-cn.com/problems/ac…
思路:并查集+去重
class UnionFind {
constructor() {
this.parent = new Map();
}
// 查找元素所在集合
find(x) {
while (this.parent.has(x)) {
x = this.parent.get(x);
}
return x;
}
// 合并两个集合
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
};
执行用时:740 ms, 在所有 JavaScript 提交中击败了35.71%的用户
内存消耗:48.8 MB, 在所有 JavaScript 提交中击败了44.44%的用户