forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
100 lines (81 loc) · 2.95 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/// Source : https://leetcode.com/problems/accounts-merge/description/
/// Author : liuyubobobo
/// Time : 2017-11-25
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Using DFS
/// Time Complexity: O(len(emails)^2)
/// Space Complexity: O(len(emails))
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
map<string, string> emailToName;
for(const vector<string>& account: accounts)
for(int i = 1 ; i < account.size() ; i ++)
emailToName[account[i]] = account[0];
unordered_map<string, int> emailIndex;
int index = 0;
for(const pair<string, string>& p: emailToName)
emailIndex.insert(make_pair(p.first, index ++));
vector<string> intToEmail(emailIndex.size(), "");
for(const pair<string, int>& p: emailIndex)
intToEmail[p.second] = p.first;
vector<unordered_set<int>> g(emailIndex.size(), unordered_set<int>());
for(const vector<string>& account: accounts){
for(int i = 1 ; i < account.size() ; i ++)
for(int j = i + 1; j < account.size() ; j ++){
int index1 = emailIndex[account[i]];
int index2 = emailIndex[account[j]];
g[index1].insert(index2);
g[index2].insert(index1);
}
}
vector<vector<string>> res;
vector<bool> flag(emailIndex.size(), false);
for(const pair<string, string>& p: emailToName){
int index = emailIndex[p.first];
if(!flag[index]){
vector<string> emails;
dfs(g, index, flag, emails, intToEmail);
sort(emails.begin(), emails.end());
string name = emailToName[emails[0]];
vector<string> tres;
tres.push_back(name);
for(const string& email: emails)
tres.push_back(email);
res.push_back(tres);
}
}
return res;
}
private:
void dfs(const vector<unordered_set<int>>& g, int v, vector<bool>& flag,
vector<string>& res, const vector<string>& intToEmail){
res.push_back(intToEmail[v]);
flag[v] = true;
for(int next: g[v])
if(!flag[next])
dfs(g, next, flag, res, intToEmail);
}
};
void printRes(const vector<vector<string>> res){
for(const vector<string>& row: res){
for(const string& e: row)
cout << e << " ";
cout << endl;
}
}
int main() {
vector<vector<string>> accounts = {
{"John", "[email protected]", "[email protected]"},
{"John", "[email protected]"},
{"John", "[email protected]", "[email protected]"},
{"Mary", "[email protected]"}
};
printRes(Solution().accountsMerge(accounts));
return 0;
}