Shu-How Zの小窝

Loading...

721.账户合并

721.账户合并

2:19:44

// 定义并查集类
class UnionFind{
    // 构造函数初始化并查集
    constructor(n){
        this.parent = new Array(n).fill(0).map((item,index)=>index)
        this.rank = new Array(n).fill(1)
        this.count = n
    }
    // 查找元素的根节点
    find(x){
        if(this.parent[x] !== x){
            this.parent[x] = this.find(this.parent[x])
        }
        return this.parent[x]
    }
    // 合并两个集合
    union(x,y){
        let rootX = this.find(x)
        let rootY = this.find(y)
        if(rootX === rootY){
            return false
        }
        if(this.rank[rootX] < this.rank[rootY]){
            this.parent[rootX] = rootY
            this.rank[rootY] += this.rank[rootX]
        }else{
            this.parent[rootY] = rootX
            this.rank[rootX] += this.rank[rootY]
        }
        this.count--
    }
    // 判断两个元素是否属于同一个集合
    connected(x,y){
        return this.find(x) === this.find(y)
    }
    // 获取集合的数量
    getCount(){
        return this.count
    }
}
/**
 * @param {string[][]} accounts
 * @return {string[][]}
 */
var accountsMerge = function(accounts) {
    const emailToIndex = new Map() // 邮箱+索引
    const emailToName = new Map() // 邮箱+姓名
    let emailsCount= 0 //初始化联通分量,邮箱里面第几个出现的
    for(const account of accounts){
        const name = account[0]
        const size= account.length
        for(let i = 1;i<size;i++){
            const email = account[i]
            if(!emailToIndex.has(email)){
                emailToIndex.set(email,emailsCount++)
                emailToName.set(email,name)
            }
        }
    }
    const uf = new UnionFind(emailsCount)
    // 自此,就把两个邮箱加名称和邮箱加坐标Map表格创建完了;拿到邮箱数量,创建并查集
    for(const account of accounts){
        const firstEmail = account[1]
        const firstEmailIndex = emailToIndex.get(firstEmail)
        const size = account.length
        for(let i = 1;i<size;i++){
            const nextEmail = account[i]
            const nextEmailIndex = emailToIndex.get(nextEmail)
            uf.union(firstEmailIndex,nextEmailIndex)
        }
    }

    const indexToEmails = new Map() //K是并查集的祖先坐标,v所有邮箱的集合;
    for(const email of emailToIndex.keys()){
        const index = uf.find(emailToIndex.get(email))
        const account = indexToEmails.get(index) || []
        account.push(email)
        indexToEmails.set(index,account)
    }
    const merged = []
    for(const emails of indexToEmails.values()){
        emails.sort()
        const name = emailToName.get(emails[0])
        const account=[]
        account.push(name)
        account.push(...emails)
        merged.push(account)
    }
    return merged
};
let accounts=[["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]];
console.log(accountsMerge(accounts))

posted @ 2025-05-06 18:26  KooTeam  阅读(16)  评论(0)    收藏  举报