|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
- 给定一个列表 accounts,每个元素 accounts[i] 是一个字符串列表,其中第一个元素 accounts[i][0] 是 名称 (name),其余元素是 emails 表示该帐户的邮箱地址。
- 现在,我们想合并这些帐户。如果两个帐户都有一些共同的邮件地址,则两个帐户必定属于同一个人。请注意,即使两个帐户具有相同的名称,它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的帐户,但其所有帐户都具有相同的名称。
- 合并帐户后,按以下格式返回帐户:每个帐户的第一个元素是名称,其余元素是按顺序排列的邮箱地址。accounts 本身可以以任意顺序返回。
- 例子 1:
- 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:
- 第一个和第三个 John 是同一个人,因为他们有共同的电子邮件 "johnsmith@mail.com"。
- 第二个 John 和 Mary 是不同的人,因为他们的电子邮件地址没有被其他帐户使用。
- 我们可以以任何顺序返回这些列表,例如答案[['Mary','mary@mail.com'],['John','johnnybravo@mail.com'],
- ['John','john00@mail.com','john_newyork@mail.com','johnsmith@mail.com']]仍然会被接受。
- 注意:
- accounts的长度将在[1,1000]的范围内。
- accounts[i]的长度将在[1,10]的范围内。
- accounts[i][j]的长度将在[1,30]的范围内。
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/accounts-merge
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- class Solution {
- private:
- vector<int>father;
- map<string, int>email_father;
- set<string> is_appear;
- public:
- //合并账户(不合并邮件,超时)
- int find_root(int x){
- if(father[x] == x)return x;
- return find_root(father[x]);
- }
- void merge(int x, int y){
- int temp1 = find_root(x);
- int temp2 = find_root(y);
- if(temp1 == temp2){
- father[temp1] = temp2;
- }else{
- father[temp2] = temp1;
- }
- }
- vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
- int len = accounts.size();
- father = vector<int>(len);
- //初始化father
- for(int i = 0; i < len; i++)father[i] = i;
-
- for(int i = 0; i < len; i++){
- for(int j = 1; j < accounts[i].size(); j++){
- if(is_appear.count(accounts[i][j]) == 0){
- is_appear.insert(accounts[i][j]);
- email_father[accounts[i][j]] = i;
- }else{
- merge(email_father[accounts[i][j]], i);
- }
- }
- }
- map<int, set<string> >store;
- for(int i = 0; i < len; i++){
- int temp = find_root(i);
- for(int j = 1; j < accounts[i].size(); j++){
- store[temp].insert(accounts[i][j]);
- }
- }
-
- vector<vector<string> >res;
- for(auto it : store){
- vector<string>temp1;
- temp1.push_back(accounts[it.first][0]);
- for(auto it1 : it.second){
- temp1.push_back(it1);
- }
- res.push_back(temp1);
- }
- return res;
- }
- };
复制代码
注意事项:合并账户(不合并邮件,超时)
|
|