-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAccount Merge
58 lines (57 loc) Β· 1.69 KB
/
Account Merge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class DisjointSet{
public:
vector<int> rank,parent;
DisjointSet(int n){
rank.resize(n+1,0);
parent.resize(n+1);
for(int i=0;i<=n;i++)parent[i]=i;
}
int findUpar(int node){
if(node==parent[node])return node;
return parent[node]=findUpar(parent[node]);
}
void Unionbyrank(int u,int v){
int u_v=findUpar(u);
int u_u=findUpar(v);
if(u_v==u_u)return;
if(rank[u_v]>rank[u_u])parent[u_u]=u_v;
else if(rank[u_v]<rank[u_u])parent[u_v]=u_u;
else{
parent[u_v]=u_u;
rank[u_u]++;
}
}
};
class Solution{
public:
vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {
int n=accounts.size();
unordered_map<string,int> helper;
DisjointSet ds(n);
for(int i=0;i<n;i++){
for(int j=1;j<accounts[i].size();j++){
string mail=accounts[i][j];
if(helper.find(mail)==helper.end())helper[mail]=i;
else ds.Unionbyrank(i,helper[mail]);
}
}
vector<vector<string>> ans;
vector<string> merged[n];
for(auto it:helper){
string mail=it.first;
int node=ds.findUpar(it.second);
merged[node].push_back(mail);
}
for(int i=0;i<n;i++){
if(merged[i].size()==0)continue;
sort(merged[i].begin(),merged[i].end());
vector<string> temp;
temp.push_back(accounts[i][0]);
for(auto it:merged[i]){
temp.push_back(it);
}
ans.push_back(temp);
}
return ans;
}
};