721. Accounts Merge (M)

Given a list of accounts where 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 common email 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.

Example 1:

Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third 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.

Example 2:

Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]

Constraints:

  • 1 <= accounts.length <= 1000

  • 2 <= accounts[i].length <= 10

  • 1 <= accounts[i][j] <= 30

  • accounts[i][0] consists of English letters.

  • accounts[i][j] (for j > 0) is a valid email.

Solution:

Version 1: Union Find with id

1.先用unionfind 把所有含有相同email的人名给放入一个连通块

2.用一个map<Integer, List>> 储存每个人名的id与其该有的所有emails的映射关系。

3.把2中的List取出来sort一下然后把id所对应的人名插入最前面, 得到新的List并插入返回答案

class UnionFind {
    private int[] father;
    
    public UnionFind(int size) {
        father = new int[size];
        for (int i = 0; i < size; i++) {
            father[i] = i;
        }
    }
    
    public int find(int a) {
        if (a == father[a]) {
            return a;
        }
        return father[a] = find(father[a]);
    }
    
    public void union(int a, int b) {
        int rootA = find(a);
        int rootB = find(b);
        if (rootA != rootB) {
            father[rootA] = rootB;
        }
    }
}

public class Solution {
    /**
     * @param accounts: List[List[str]]
     * @return: return a List[List[str]]
     */
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        // write your code here
        List<List<String>> res = new ArrayList<>();
        if (accounts.size() == 0) {
            return res;
        }
        
        UnionFind uf = new UnionFind(accounts.size());
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < accounts.size(); i++) {
            List<String> account = accounts.get(i);
            for (int j = 1; j < account.size(); j++) {
                String email = account.get(j);
                map.putIfAbsent(email, i);
                uf.union(map.get(email), i);
            }
        }
        
        HashMap<Integer, List<String>> indexEmail = new HashMap<>();
        for (String email : map.keySet()) {
            int root = uf.find(map.get(email));
            indexEmail.putIfAbsent(root, new ArrayList<>());
            indexEmail.get(root).add(email);
        }
        
        for (Integer index : indexEmail.keySet()) {
            List<String> account = new ArrayList<>();
            account.add(accounts.get(index).get(0));
            
            List<String> emails = indexEmail.get(index);
            Collections.sort(emails);
            
            account.addAll(emails);
            res.add(account);
        }
        
        return res;
    }
}

Version 2: Union Find 2 with String

复杂度分析

  • 时间复杂度O(n)

    • 用了路径压缩,查询效率为O(1)

  • 空间复杂度O(n)

    • n为邮箱的数目

javac++python

public class Solution {
    /**
     * @param accounts: List[List[str]]
     * @return: return a List[List[str]]
     */
    private Map<String, String> father = new HashMap<String, String>();
    private Map<String, String> owner = new HashMap<String, String>();
    private Map<String, TreeSet<String>> mp = new HashMap<>();
    
    private String find(String s) {
        if (father.get(s) == s) {
            return s;
        }
        //path compression
        father.put(s, find(father.get(s)));
        return father.get(s);
    }
    private void connect(String a,String b) {
        String fa = find(a);
        String fb = find(b);
        if (fa!=(fb)) {
            father.put(fa,fb);
        }
    }
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        List<List<String>> result = new ArrayList<>();
        for (List<String> account:accounts) {
            for (int i = 0; i < account.size(); i++) {
                father.put(account.get(i), account.get(i));
                owner.put(account.get(i), account.get(0));
            }
        }
        // union all the emails under the same account
        for (List<String> account:accounts) {
            for (int i = 2; i < account.size(); i++) {
                // let email1 be the root of all other emails under the same account
                connect(account.get(i),account.get(1));
            }
        }
        
        for (List<String> account:accounts) {
            String tmp = find(account.get(1));
            if (!mp.containsKey(tmp)) {
                    mp.put(tmp, new TreeSet<>());
                }
            for (int i = 1; i < account.size(); i++) {
                //account[1] <-> set of account[i]s
                mp.get(tmp).add(account.get(i));
            }
        }
        for(String key : mp.keySet()){
            List<String> record = new ArrayList(mp.get(key));
            record.add(0, owner.get(key));
            result.add(record);
        }
        return result;
    }
}

Last updated