forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0721.cpp
More file actions
71 lines (51 loc) · 1.79 KB
/
Copy path0721.cpp
File metadata and controls
71 lines (51 loc) · 1.79 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
class UnionFind{
unordered_map<string, string> connection;
public:
void unions(string x, string y){
if(connection.count(x) == 0)
connection[x] = x;
if(connection.count(y) == 0)
connection[y] = y;
string par_x = find(x);
string par_y = find(y);
connection[par_x] = par_y;
}
string find(string s){
if(connection[s] != s)
connection[s] = find(connection[s]);
return connection[s];
}
bool isRepresentative(string s){
return connection[s] == s;
}
vector<string> getGroupEmails(string remail) {
vector<string> eList;
for(auto email : connection)
if(find(email.first) == remail)
eList.push_back(email.first);
return eList;
}
};
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
UnionFind *unionFind = new UnionFind();
unordered_map<string, string> owner;
for(auto &account : accounts) {
for(int i = 1; i < account.size(); i++) {
owner[account[i]] = account[0];
unionFind -> unions(account[i], account[1]);
}
}
vector<vector<string>> res;
for(auto itr : owner) {
if(unionFind -> isRepresentative(itr.first)) {
vector<string> temp = unionFind -> getGroupEmails(itr.first);
sort(temp.begin(), temp.end());
temp.insert(temp.begin(), itr.second);
res.push_back(temp);
}
}
return res;
}
};