721. 账户合并
给定一个列表 accounts,每个元素 accounts[i] 是一个字符串列表,其中第一个元素 accounts[i][0] 是 名称 (name),其余元素是 emails 表示该账户的邮箱地址。
现在,我们想合并这些账户。如果两个账户都有一些共同的邮箱地址,则两个账户必定属于同一个人。请注意,即使两个账户具有相同的名称,它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的账户,但其所有账户都具有相同的名称。
合并账户后,按以下格式返回账户:每个账户的第一个元素是名称,其余元素是按顺序排列的邮箱地址。账户本身可以以任意顺序返回。
示例 1:
输入:
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
输出:
[["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
解释:
第一个和第三个 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~
解题思路
- 题目要找到 account 之间的关系(是不是属于同一个人),还是用「并查集」搞定
- 遍历所有邮箱,用 Hash 表存储每个邮箱,key 为邮箱、value 为 accounts 角标。如果当前邮箱存在 Hash 表中,说明当前账户属于之前的某个人,把当前角标和 Hash 表中的角标 union 在一起。
- 根据并查集的内容合并账户,拥有同一个父亲的账户属于同一个人。
参考代码
public List<List<String>> accountsMerge(List<List<String>> accounts) {
int n = accounts.size();
// email2Account:key为email,value为accounts角标,判断那些账户属于同一个人
Map<String, Integer> email2Account = new HashMap<>(n);
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < n; i++) {
List<String> account = accounts.get(i);
for (int j = 1; j < account.size(); j++) {
if (email2Account.containsKey(account.get(j))) {
unionFind.union(email2Account.get(account.get(j)), i);
continue;
}
email2Account.put(account.get(j), i);
}
}
// 合并账户,用 Set去重
Map<Integer, Set<String>> map = new HashMap<>(n);
for (int i = 0; i < n; i++) {
map.computeIfAbsent(unionFind.find(i), k -> new HashSet<>()).addAll(accounts.get(i));
}
// 组装数据,名字 + 排序邮箱(调试了几次才知道邮箱要排序。。。)
List<List<String>> ans = new ArrayList<>();
for (Map.Entry<Integer, Set<String>> entry : map.entrySet()) {
List<String> account = new ArrayList<>();
String name = accounts.get(entry.getKey()).get(0);
entry.getValue().remove(name);
List<String> email = new ArrayList<>(entry.getValue());
Collections.sort(email);
account.add(name);
account.addAll(email);
ans.add(account);
}
return ans;
}
class UnionFind {
private int[] parent;
public UnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public void union(int x, int y) {
parent[find(x)] = find(y);
}
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
}
执行结果