Skip to content

Commit d07cf7e

Browse files
authored
Create accounts-merge.cpp
1 parent 63df7fb commit d07cf7e

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

C++/accounts-merge.cpp

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Time: O(nlogn), n is the number of total emails, and the max length of email is 320, p.s. {64}@{255}
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
7+
UnionFind union_find;
8+
unordered_map<string, string> email_to_name;
9+
unordered_map<string, int> email_to_id;
10+
for (const auto& account : accounts) {
11+
const auto& name = account[0];
12+
for (int i = 1; i < account.size(); ++i) {
13+
if (!email_to_id.count(account[i])) {
14+
email_to_name[account[i]] = name;
15+
email_to_id[account[i]] = union_find.get_id();
16+
}
17+
union_find.union_set(email_to_id[account[1]], email_to_id[account[i]]);
18+
}
19+
}
20+
21+
unordered_map<int, set<string>> lookup;
22+
for (const auto& kvp : email_to_name) {
23+
const auto& email = kvp.first;
24+
lookup[union_find.find_set(email_to_id[email])].emplace(email);
25+
}
26+
vector<vector<string>> result;
27+
for (const auto& kvp : lookup) {
28+
const auto& emails = kvp.second;
29+
vector<string> tmp{email_to_name[*emails.begin()]};
30+
for (const auto& email : emails) {
31+
tmp.emplace_back(email);
32+
}
33+
result.emplace_back(move(tmp));
34+
}
35+
return result;
36+
}
37+
38+
private:
39+
class UnionFind {
40+
public:
41+
int get_id() {
42+
set_.emplace_back(set_.size());
43+
return set_.size() - 1;
44+
}
45+
46+
int find_set(const int x) {
47+
if (set_[x] != x) {
48+
set_[x] = find_set(set_[x]); // Path compression.
49+
}
50+
return set_[x];
51+
}
52+
53+
void union_set(const int x, const int y) {
54+
int x_root = find_set(x), y_root = find_set(y);
55+
if (x_root != y_root) {
56+
set_[min(x_root, y_root)] = max(x_root, y_root);
57+
}
58+
}
59+
60+
private:
61+
vector<int> set_;
62+
};
63+
};

0 commit comments

Comments
 (0)