JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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","[email protected]","[email protected]"],["John","[email protected]","[email protected]"],["Mary","[email protected]"],["John","[email protected]"]]
Output: [["John","[email protected]","[email protected]","[email protected]"],["Mary","[email protected]"],["John","[email protected]"]]
Explanation:
The first and third John's are the same person as they have the common email "[email protected]".
The second 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', '[email protected]'], ['John', '[email protected]'],
['John', '[email protected]', '[email protected]', '[email protected]']] would still be accepted.

Example 2:

Code

class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        UnionFind unionFind = new UnionFind(10000);
        Map<String, String> emailToName = new HashMap<>();
        Map<String, Integer> emailToID = new HashMap<>();

        int id = 0;
        for (List<String> account : accounts) {
            String name = account.get(0);
            String rootEmail = account.get(1);
            for (int i = 1; i < account.size(); i++) {
                String email = account.get(i);

                emailToName.put(email, name);
                if (!emailToID.containsKey(email)) {
                    emailToID.put(email, id++);
                }
                // use first email as the root
                // union all emails for this account
                unionFind.union(emailToID.get(rootEmail), emailToID.get(email));
            }
        }

        Map<Integer, List<String>> res = new HashMap<>();

        for (String email : emailToName.keySet()) {
            // get root email
            int index = unionFind.find(emailToID.get(email));
            if (!res.containsKey(index)) {
                res.put(index, new ArrayList<>());
            }

            res.get(index).add(email);
        }

        for (List<String> emails : res.values()) {
            Collections.sort(emails);
            emails.add(0, emailToName.get(emails.get(0)));
        }

        return new ArrayList<>(res.values());
    }
}

class UnionFind {
    int[] parents;
    int[] ranks;

    public UnionFind(int n) {
        parents = new int[n];
        ranks = new int[n];

        for (int i = 0; i < n; i++) {
            parents[i] = i;
            ranks[i] = 1;
        }
    }

    public boolean union(int x, int y) {
        int xParent = find(x);
        int yParent = find(y);
        // same parent
        if (xParent == yParent)
            return false;
        // different parent
        if (ranks[xParent] > ranks[yParent]) {
            parents[yParent] = xParent;
        } else if (ranks[xParent] < ranks[yParent]) {
            parents[xParent] = yParent;
        } else {
            parents[yParent] = xParent;
            ranks[xParent]++;
        }

        return true;
    }

    public int find(int node) {
        while (node != parents[node]) {
            int parentNode = parents[parents[node]];
            // update parents array
            parents[node] = parentNode;
            node = parentNode;
        }

        return node;
    }
}
class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        Map<String, String> emailToName = new HashMap<>();
        Map<String, ArrayList<String>> graph = new HashMap<>();

        for (List<String> account : accounts) {
            String name = account.get(0);
            String rootEmail = account.get(1);
            for (int i = 1; i < account.size(); i++) {
                String email = account.get(i);

                graph.computeIfAbsent(email, x -> new ArrayList<>()).add(rootEmail);

                graph.computeIfAbsent(rootEmail, x -> new ArrayList<>()).add(email);

                emailToName.put(email, name);
            }
        }

        Set<String> seen = new HashSet<>();
        List<List<String>> ans = new ArrayList<>();

        for (String email : graph.keySet()) {
            if (!seen.contains(email)) {
                seen.add(email);

                Queue<String> queue = new LinkedList<>();
                queue.offer(email);

                List<String> emails = new ArrayList<>();
                while (!queue.isEmpty()) {
                    String node = queue.poll();
                    emails.add(node);
                    for (String nei : graph.get(node)) {
                        if (!seen.contains(nei)) {
                            seen.add(nei);
                            queue.offer(nei);
                        }
                    }
                }

                Collections.sort(emails);
                emails.add(0, emailToName.get(email));
                ans.add(emails);
            }
        }

        return ans;
    }
}