Accounts Merge

题目
Given a list accounts, 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 email that is common 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.

答案

class Solution {
    private int find(int index, List list) {
        int p = list.get(index);
        return (p == index) ? index : find(p, list);
    }


    public List> accountsMerge(List> accounts) {
        int num_accounts = accounts.size();
        // Initially, each account is independent
        List parent = new ArrayList();
        List> ret = new ArrayList<>();
        Map map = new HashMap<>();
        Map> map2 = new HashMap<>();


        for(int i = 0; i < num_accounts; i++) parent.add(i);

        for(int i = 0; i < num_accounts; i++) {
            List curr_account = accounts.get(i);
            for(int j = 1; j < curr_account.size(); j++) {
                String email = curr_account.get(j);
                if(map.get(email) != null) {
                    int email_owner = map.get(email);
                    int email_owner_parent = find(email_owner, parent);
                    int i_parent = find(i, parent);
                    if(i_parent != email_owner_parent) parent.set(email_owner_parent, i_parent);
                }
                else {
                    map.put(email, i);
                }
            }
        }

        for(Map.Entry entry : map.entrySet()) {
            String email = entry.getKey();
            int email_owner = entry.getValue();
            int email_owner_parent = find(email_owner, parent);

            map2.putIfAbsent(email_owner_parent, new ArrayList());
            // Add name and email
            if(map2.get(email_owner_parent).size() == 0) map2.get(email_owner_parent).add(accounts.get(email_owner_parent).get(0));
            map2.get(email_owner_parent).add(email);
        }

        for(Map.Entry> entry : map2.entrySet()) {
            int email_owner_parent = entry.getKey();
            List name_emails = entry.getValue();
            Collections.sort(name_emails.subList(1, name_emails.size()));
            ret.add(name_emails);
        }
        return ret;
    }
}

你可能感兴趣的:(Accounts Merge)