一、题目
给定一个列表 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]的范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/accounts-merge
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、分析及代码
1. 并查集+哈希表
(1)思路
用哈希表记录邮箱和账户的对应关系,通过并查集对具有相同邮箱的账户进行合并。
(2)代码
class Solution {
public List<List<String>> accountsMerge(List<List<String>> accounts) {
List<List<String>> ans = new LinkedList<List<String>>();//记录答案
Map<String, Integer> map = new HashMap<>();//记录各邮箱对应账户索引位置
int accountLen = accounts.size();
int [] parent = new int[accountLen];//针对账户索引的并查集
for (int i = 0; i < accountLen