[路飞][LeetCode]721_账户合并

365 阅读3分钟

「这是我参与2022首次更文挑战的第17天,活动详情查看:2022首次更文挑战

看一百遍美女,美女也不一定是你的。但你刷一百遍算法,知识就是你的了~~

谁能九层台,不用累土起!

题目地址

题目

给定一个列表 accounts,每个元素 accounts[i] 是一个字符串列表,其中第一个元素 accounts[i][0] 是 名称 (name) ,其余元素是 emails 表示该账户的邮箱地址。

现在,我们想合并这些账户。如果两个账户都有一些共同的邮箱地址,则两个账户必定属于同一个人。请注意,即使两个账户具有相同的名称,它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的账户,但其所有账户都具有相同的名称。

合并账户后,按以下格式返回账户:每个账户的第一个元素是名称,其余元素是 按字符 ASCII 顺序排列 的邮箱地址。账户本身可以以 任意顺序 返回。

示例 1:

输入: accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
输出: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
解释:
第一个和第三个 John 是同一个人,因为他们有共同的邮箱地址 "johnsmith@mail.com"。 
第二个 JohnMary 是不同的人,因为他们的邮箱地址没有被其他帐户使用。
可以以任何顺序返回这些列表,例如答案 [['Mary''mary@mail.com']['John''johnnybravo@mail.com']['John''john00@mail.com''john_newyork@mail.com''johnsmith@mail.com']] 也是正确的。

示例 2:

输入: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
输出: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]

提示:

  • 1 <= accounts.length <= 1000
  • 2 <= accounts[i].length <= 10
  • 1 <= accounts[i][j].length <= 30
  • accounts[i][0] 由英文字母组成
  • accounts[i][j] (for j > 0) 是有效的邮箱地址

解题思路

本题我们重点使用Map和并查集。

  • 首先我们先将所有的非重复邮箱拎出来,用两个map结构来分别存储每个邮箱的标记,以及对应的用户名。

  • 使用邮箱的个数来初始化并查集

  • 通过账号中的邮箱,进行合并标记

  • 对标记后的邮箱进行分组,排序,添加用户名

  • 输出结果

解题代码

var accountsMerge = function(accounts) {
    const nameMap = new Map()
    const indexMap = new Map()
    let count = 0
    accounts.forEach(account=>{
        for(let i =1;i<account.length;i++){  // 只循环邮箱
            const email = account[i]
            if(!indexMap.has(email)){ // 对于非重复邮箱进行操作
                nameMap.set(email,account[0]) // 邮箱 -> 用户名对应 
                indexMap.set(email,count++) // 邮箱 ->唯一索引对应
            }
        }
    })

    const union = new UnionFind(count)  // 初始化并查集
    accounts.forEach(account=>{
        const firstIndex = indexMap.get(account[1])
        for(let i =2;i<account.length;i++){ // 对账号的每个邮箱尝试合并操作
            const secondIndex = indexMap.get(account[i])
            union.merge(firstIndex,secondIndex)
        }
    })
    // 最终会将同账号的邮箱标记为一样

    const indexToEmails = new Map();
    [...indexMap.keys()].forEach(key=>{ // key -> 邮箱
        const index =  union.find(indexMap.get(key))  // 获取邮箱对应的索引在并查集中的标记
        const account = indexToEmails.get(index)||[] // 用并查集中的标记将邮箱进行分组存储
        account.push(key)
        indexToEmails.set(index,account)
    })
    const result = [];
     [...indexToEmails.keys()].forEach(key=>{ // key -> 并查集中的标记
        const emails = indexToEmails.get(key).sort() // 获取邮箱并进行排序
        const name = nameMap.get(emails[0])  // 根据邮箱,获取邮箱对应的用户名
        result.push([name, ...emails]);  // 组装数据
    })
    return result  // 输出结果
};  

// 并查集
class UnionFind {
    constructor(len){
        this.parents = new Array(len).fill(0).map((v,i)=>i)
        this.rank =  new Array(len).fill(0)
    }
    find(i){ // 查找根节点
        if(this.parents[i] == i ) return i
        return this.find(this.parents[i])
    }
    connect(a,b){ // 判断是否相连
        return this.find(a) == this.find(b)
    }
    merge(a,b){ // 合并
        if(this.connect(a,b)) return
        const fa = this.find(a)
        const fb = this.find(b)
        if(this.rank[fa]>this.rank[fb]){
            this.parents[fb] = fa
        }else{
            this.parents[fa] = fb
            if(this.rank[fa]==this.rank[fb] ){
                this.rank[fb]++
            }
        }
    }
}

本题确实思考了很久,才整理出这篇文章,希望能对你有一点帮助。

如有任何问题或建议,欢迎留言讨论!