forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path721.accounts-merge.cpp
79 lines (69 loc) · 1.71 KB
/
721.accounts-merge.cpp
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
72
73
74
75
76
77
78
79
class UnionFind
{
vector<int> graph;
public:
UnionFind(int n){
graph.resize(n);
for (int i = 0; i < n; i++)
{
graph[i] = i;
}
}
int find(int node)
{
if (graph[node] == node)
{
return node;
}
graph[node] = find(graph[node]);
return graph[node];
}
void connect(int a, int b)
{
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b)
{
graph[root_a] = root_b;
}
}
};
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
// email: userId
unordered_map<string, int> accoutMap;
// mapping and connect
UnionFind uf(accounts.size());
for (int i = 0; i < accounts.size(); ++i)
{
for (int j = 1; j < accounts[i].size(); ++j)
{
string email = accounts[i][j];
if (accoutMap.count(email) == 0)
{
accoutMap[email] = i;
}
else
{
int userId = accoutMap[email];
uf.connect(i, userId);
}
}
}
// merge
unordered_map<int, set<string>> merged;
for (int i = 0; i < accounts.size(); ++i)
{
int k = uf.find(i);
merged[k].insert(accounts[i].begin(), accounts[i].end());
}
// answer
vector<vector<string>> res;
for (auto it: merged)
{
res.push_back(vector<string>(it.second.begin(), it.second.end()));
}
return res;
}
};