계정 통합

계정 목록이 주어졌습니다.C C O U N t 각 요소계정 [I] 계정 [I]a c c o u n t s [ i ] 는 문자열 목록입니다. 여기서 첫 번째 요소는[i] [0] 계정 [i] [0]입니다.a c c o u n t s [ i ] [ 0 ] 은 이름 (이름)이고 나머지 요소는 이메일 (계정의 이메일 주소)입니다.

이제 이러한 계정을 병합하려고합니다. 두 계정에 공통 이메일 주소가있는 경우 두 계정은 같은 사람의 것이어야합니다. 두 계정의 이름이 같더라도 사람이 같은 이름을 가질 수 있으므로 다른 사람에게 속할 수 있습니다. 사람은 처음에 여러 계정을 가질 수 있지만 모든 계정의 이름은 동일합니다.

계정이 병합 된 후 계정은 다음 형식으로 반환됩니다. 각 계정의 첫 번째 요소는 이름이고 나머지 요소는 순서대로 이메일 주소입니다. 계정 자체는 어떤 순서로든 반환 할 수 있습니다.

예 1 :

시작하다:

accounts = [["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"]]

산출:

[["John", '[email protected]', '[email protected]', '[email protected]'],  ["John", "[email protected]"], ["Mary", "[email protected]"]]
解释:
第一个和第三个 John 是同一个人,因为他们有共同的邮箱地址 "[email protected]"。 
第二个 John 和 Mary 是不同的人,因为他们的邮箱地址没有被其他帐户使用。
可以以任何顺序返回这些列表,例如答案 [['Mary''[email protected]']['John''[email protected]']['John''[email protected]''[email protected]''[email protected]']] 也是正确的。

신속한:

계정 계정 길이 C C O는 U가 N t S 의 것[1, 1000] (1) 1000][ 1 , 1 0 0 0 ] .
계정 [i] 계정 [i]a c c o u n t s [ i ]의 길이는[1, 10] [1, 10]입니다.[ 1 , 1 0 ] .
계정 [i] [j] 계정 [i] [j]a c c o u n t s [ i ] [ j ]의 길이는[1, 30] [1, 30]입니다.[ 1 , 3 0 ] .

class Solution {
    
    
public:
    int f[10000];
    int find(int x){
    
    
        return x==f[x]?x:f[x]=find(f[x]);
    }
    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
    
    
        int n=accounts.size();
        unordered_map<string,int>ma;
        for (int i=0;i<10000;i++){
    
    
            f[i]=i;
        }
        for (int i=0;i<n;i++){
    
    
            int m=accounts[i].size();
            for (int j=1;j<m;j++){
    
    
                if (ma.count(accounts[i][j])==0){
    
    
                    ma[accounts[i][j]]=i;
                }
                f[find(i)]=find(ma[accounts[i][j]]);
            }
        }
        unordered_map<int,vector<string> >ma1;
        for (auto &[str,i]:ma){
    
    
            ma1[find(i)].push_back(str);
        }
        vector<vector<string>>res;
        for (auto &[i,vec]:ma1){
    
    
            sort(vec.begin(),vec.end());
            vector<string>tmp;
            tmp.push_back(accounts[find(i)][0]);
            tmp.insert(tmp.end(),vec.begin(),vec.end());
            res.push_back(tmp);
        }
        return res;
    }
};

추천

출처blog.csdn.net/weixin_43601103/article/details/112763190