721. 账户合并

并查集就能实现,我都忘了并查集了,唉

用map记录每个邮箱的账号,再此之前判断该邮箱是否已经在map中有value,即该邮箱是否已经标记了账户

如果有,那就将当前邮箱的所有账号,转移到标记的账户

如果当前账户下的多个邮箱在map中有不同的value,那就统一转移到第一个value即可

用set存储每个邮箱的账户

class Solution {
public:

    set<string> s[1010];
    vector<vector<string>> ret;
    map<string, int> mmap;
    int vis[1010];
    void move(int flag, int k)
    {
        flag -= 1;
        k -= 1;
        vis[k] = 0;
        for(set<string>::iterator it = s[k].begin(); it != s[k].end(); it++)
        {
            s[flag].insert(*it);
            mmap[*it] = flag + 1;
        }
    }

    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
        int len1 = accounts.size();
        memset(vis, 0, sizeof(vis));
        for(int i = 0; i < len1; i++)
        {
            int len2 = accounts[i].size();
            int flag = -1;
            for(int j = 1; j < len2; j++)
            {
                if(mmap[accounts[i][j]])
                {
                    if(flag == -1)
                        flag = mmap[accounts[i][j]];
                    else if(mmap[accounts[i][j]] != flag)
                        move(flag, mmap[accounts[i][j]]);
                }
            }
            if(flag == -1)
            {
                vis[i] = 1;
                for(int j = 1; j < len2; j++)
                {
                    s[i].insert(accounts[i][j]);
                    mmap[accounts[i][j]] = i + 1;
                }
            }
            else
            {
                for(int j = 1; j < len2; j++)
                {
                    s[flag - 1].insert(accounts[i][j]);
                    mmap[accounts[i][j]] = flag;
                }
            }
        }

        int ans = 0;
        vector<string> v;
        for(int i = 0; i < len1; i++)
        {
            v.clear();
            if(vis[i])
            {
                // cout << 111 << endl;                
                v.push_back(accounts[i][0]);
                for(set<string>::iterator it = s[i].begin(); it != s[i].end(); it++)
                {
                    v.push_back(*it);
                }
                ret.push_back(v);
            }
        }
        return ret;

    }
};

 

上一篇:linux内核那些事之mmap_region流程梳理


下一篇:[Linux 高并发服务器] 内存映射