题目概述
给定一个列表 accounts
,每个元素 accounts[i]
是一个字符串列表,其中第一个元素 accounts[i][0]
是 名称 (name),其余元素是 emails,表示该账户的邮箱地址。
现在,我们想合并这些账户。如果两个账户都有一些共同的邮箱地址,则两个账户必定属于同一个人。请注意,即使两个账户具有相同的名称,它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的账户,但其所有账户都具有相同的名称。
合并账户后,按以下格式返回账户:每个账户的第一个元素是名称,其余元素是按字符 ASCII 顺序排列的邮箱地址。账户本身可以以任意顺序返回。
示例 1:
输入:
accounts = [["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"]]
输出: [["John", '[email protected]', '[email protected]', '[email protected]'], ["John", "[email protected]"], ["Mary", "[email protected]"]]
解释:
第一个和第三个 John 是同一个人,因为他们有共同的邮箱地址 "[email protected]"。
第二个 John 和 Mary 是不同的人,因为他们的邮箱地址没有被其他帐户使用。
可以以任何顺序返回这些列表,例如答案 [['Mary','[email protected]'],['John','[email protected]'],
['John','[email protected]','[email protected]','[email protected]']] 也是正确的。
提示:
accounts
的长度将在[1,1000]
的范围内。accounts[i]
的长度将在[1,10]
的范围内。accounts[i][j]
的长度将在[1,30]
的范围内。
解题思路
本题可以使用并查集解决,具体什么是并查集,可以看看这篇博客 https://blog.csdn.net/bjweimengshu/article/details/108332389
根据题目要求,两个账户只要有一个邮箱相同,那么就认为是同一个人,因此我们以下标表示用户,把所有属于同一个人的用户(下标)使用并查集连接起来,接下来嘛 。。。我也不知道怎么描述,看代码吧
class Solution {
public List<List<String>> accountsMerge(List<List<String>> accounts) {
// 创建一个 HashMap,通过下列的循环操作可以得知
// 最终每个邮箱都会对应它所属的某一个用户id
Map<String, Integer> emailToId = new HashMap<>();
int accountsLen = accounts.size();
UnionFind union = new UnionFind(accountsLen);
for(int i = 0; i < accountsLen; i++) {
int emailsLen = accounts.get(i).size();
for(int j = 1; j < emailsLen; j++) {
String curEmail = accounts.get(i).get(j);
if(emailToId.containsKey(curEmail)) {
union.merge(emailToId.get(curEmail), i);
} else {
emailToId.put(curEmail, i);
}
}
}
// 将用户id与其拥有的所有email对应起来
Map<Integer, List<String>> idToEmail = new HashMap<>();
for(Map.Entry<String, Integer> entry : emailToId.entrySet()) {
// 首先要找到父id
int id = union.getFather(entry.getValue());
// 父id拥有的emails一定是连接集合中所有用户所共有的
List<String> emails = idToEmail.getOrDefault(id, new LinkedList<>());
// 再把缺少的email添加到emails中
emails.add(entry.getKey());
idToEmail.put(id, emails);
}
// 将id与用户名对应即可
List<List<String>> result = new LinkedList<>();
for (Map.Entry<Integer,List<String>> entry : idToEmail.entrySet()) {
List<String> list = entry.getValue();
Collections.sort(list);
list.add(0, accounts.get(entry.getKey()).get(0));
result.add(list);
}
return result;
}
class UnionFind {
int[] f;
public UnionFind(int n) {
f = new int[n];
for(int i = 0; i < n; i++) {
f[i] = i;
}
}
public int getFather(int index) {
return f[index] == index ? index : getFather(f[index]);
}
public void merge(int index1, int index2) {
f[getFather(index1)] = getFather(index2);
}
}
}