https://leetcode.com/problems/accounts-merge/description/
vector<vector<string>> accountsMerge(vector<vector<string>>& a) {
int N = a.size();
if(N<=1) return a;
vector<int> person(N);
for(int i=0; i<N; i++) person[i] = i;
unordered_map<string, int> m1;
for(int i=0; i<N; i++) {
vector<string> vs = a[i];
for(int j=1; j<vs.size(); j++) {
if(m1.count(vs[j])) {
int k = m1[vs[j]];
while(k != person[k]) k = person[k];
person[k] = i;
}
m1[vs[j]] = i;
}
}
unordered_map<int, set<string>> m2;
vector<int> id(N, -1);
for(int i=0; i<N; i++) {
int k = person[i];
while(k!=person[k]) k=person[k];
for(int j=1; j<a[i].size(); j++) m2[k].insert(a[i][j]);
}
vector<vector<string>> res;
for(auto& m : m2) {
vector<string> vs;
vs.push_back(a[m.first][0]);
for(auto& s: m.second) {
vs.push_back(s);
}
res.push_back(vs);
}
return res;
}
No comments:
Post a Comment