其他分享
首页 > 其他分享> > 我的力扣算发721-账户合并

我的力扣算发721-账户合并

作者:互联网

ok
看题:
给定一个列表 accounts,每个元素 accounts[i] 是一个字符串列表,其中第一个元素 accounts[i][0] 是 名称 (name),其余元素是 emails 表示该账户的邮箱地址。
现在,我们想合并这些账户。如果两个账户都有一些共同的邮箱地址,则两个账户必定属于同一个人。请注意,即使两个账户具有相同的名称,它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的账户,但其所有账户都具有相同的名称。
合并账户后,按以下格式返回账户:每个账户的第一个元素是名称,其余元素是按顺序排列的邮箱地址。账户本身可以以任意顺序返回。

在这里插入图片描述

代码:

class Solution {
public:
    static const int N = 1010;
    int p[N];
    unordered_map<string, int> father;
    vector<vector<string>> res;
public:
    int find(int a)
    {
        if(p[a] != a)
            p[a] = find(p[a]);
        return p[a];
    }
    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
        int n = accounts.size();
        for(int i = 0; i < n; i++)
            p[i] = i;
        for(int i = 0; i < n; i++)
            for(int j = 1; j < accounts[i].size(); j++)
            {
                string email = accounts[i][j];
                if(father.count(email))
                    p[find(father[email])] = p[i];
                else
                    father[email] = i;
            }
        unordered_map<int, set<string>> m;
        for(int i = 0; i < n; i++)
        {
            int t = find(i);
            for(int j = 1; j < accounts[i].size(); j++)
                m[t].insert(accounts[i][j]);
        }
        for(auto& p: m)
        {
            vector<string> ans;
            ans.push_back(accounts[p.first][0]);
            for(string email : p.second)
                ans.push_back(email);
            res.push_back(ans);
        }
        return res;
    }
};

没时间解释了,溜了溜了

标签:账户,扣算发,ans,++,int,accounts,721,email
来源: https://blog.csdn.net/weixin_46108213/article/details/112761447