题目描述
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
样例
Input:
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
Explanation:
The first and third John's are the same person as they have the common email "johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
算法1m
(Union Find) $O(n*m)$
把每一个account初始化一个person_id,对其邮箱进行find和union。用hashmap来存储person_id与多个邮箱的关系。最后把hashmap的数据输出到二维数组即可。
时间复杂度
遍历每一行的字符串,O(nm)
需要数组,hashmap来存图,O(nm)
参考文献
C++ 代码
class Solution {
public:
int find(vector<int> &union_find, int ind) {
if (union_find[ind] != ind){
union_find[ind] = find(union_find, union_find[ind]);
}
return union_find[ind];
}
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
vector<int> person_id (accounts.size(), 0);
unordered_map<string, int> emailIdtoId; //{email, personId}
for (int i=0; i<accounts.size(); ++i){
person_id[i] = i;
for (int j=1; j<accounts[i].size(); ++j){
if (emailIdtoId.count(accounts[i][j])){
int root1 = find(person_id, i);
int root2 = find(person_id, emailIdtoId[accounts[i][j]]);
person_id[root1] = root2;
}else{
emailIdtoId[accounts[i][j]] = person_id[i];
}
}
}
unordered_map<int, vector<string>> res_map;//{person_id, email}
for (auto it : emailIdtoId){
int ind = find(person_id, it.second);
res_map[ind].push_back(it.first);
}
vector<vector<string>> res;
for (auto it : res_map){
vector<string> email = it.second;
sort(email.begin(), email.end());
email.insert(email.begin(), accounts[it.first][0]);
res.push_back(email);
}
return res;
}
};