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.

Example 1:

Input: 
accounts = [["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"]]
Output: [["John", '[email protected]', '[email protected]', '[email protected]'],  ["John", "[email protected]"], ["Mary", "[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.

Note:

  • The length of accounts will be in the range [1, 1000].
  • The length of accounts[i] will be in the range [1, 10].
  • The length of accounts[i][j] will be in the range [1, 30].

思路1:经典的union find题目。注意:此时union find的是accounts的index,0,1,2,如果后面email有相同的,则这一行的index应该union为parents的。然后再根据index相同来收集emails。看懂了之后,再自己写就好写了,算法关键还是懂原理,代码都是其次的。

Accounts Merge

class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        if(accounts == null || accounts.size() == 0) {
            return new ArrayList<List<String>>();
        }
        int[] parents = new int[accounts.size()];
        for(int i=0; i<accounts.size(); i++){
            parents[i] = i;
        }
        
        HashMap<String, Integer> owners = new HashMap<String, Integer>();
        for(int i=0; i<accounts.size(); i++){
            for(int j=1; j<accounts.get(i).size(); j++){
                String email = accounts.get(i).get(j);
                if(!owners.containsKey(email)){
                    owners.put(email, i);
                } else {
                    // if contains same email, union parent index;
                    int person = owners.get(email);
                    int rootP = findParent(parents, person);
                    int rootQ = findParent(parents, i);
                    if(rootP != rootQ){
                        parents[rootP] = rootQ;
                    }
                }
            }
        }
        
        // group emails belongs to same root;
        HashMap<Integer, TreeSet<String>> users = new HashMap<Integer, TreeSet<String>>();
        for(int i=0; i<accounts.size(); i++){
            if(users.containsKey(i)){
                users.get(i).addAll(accounts.get(i).subList(1, accounts.get(i).size()));
            } else {
                int parent = findParent(parents, i); // 应该用parent的index来收集,这个很容易弄错。
                TreeSet<String> set = new TreeSet<String>();
                users.putIfAbsent(parent, set); // 这里应该提前加入一个空的,后面好写.
                List<String> emails = accounts.get(i);
                users.get(parent).addAll(emails.subList(1,emails.size())); 
            }
        }
        
        // construct result;
        List<List<String>> result = new ArrayList<List<String>>();
        for(Integer i: users.keySet()){
            String name = accounts.get(i).get(0);
            List<String> list = new ArrayList<>(users.get(i));
            list.add(0, name);
            result.add(list);
        }
        return result;
    }
    
    public int findParent(int[] parents, int i){
        while(i!=parents[i]){
            parents[i] = parents[parents[i]]; // Path compression. Princeton 算法课上学的。
            i = parents[i];
        }
        return i;
    }
}

思路2:这题还可以作为graph的题目来做,email变成node,name之后可以建立一个图,name单独store出来,然后用email node来做dfs,收集在一条path上面的email,然后最后construct result。

Accounts Merge

class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        List<List<String>> lists = new ArrayList<List<String>>();
        if(accounts == null || accounts.size() == 0) {
            return lists;
        }
        
        // Build Graph; [emailNode, adjcentNodeList]
        HashMap<String,TreeSet<String>> graph = new HashMap<String, TreeSet<String>>();
        // Store name, EmailToName mapping;
        HashMap<String, String> emailToName = new HashMap<String, String>();
        for(List<String> account: accounts){
            String name = account.get(0);
            for(int i=1; i<account.size(); i++){
                String email = account.get(i);
                emailToName.put(email,name);
                graph.putIfAbsent(email, new TreeSet<String>());
                if(i!=1){
                    graph.get(account.get(i)).add(account.get(i-1));
                    graph.get(account.get(i-1)).add(account.get(i));
                }
            }
        }
        
        Set<String> visited = new HashSet<String>();
        // DFS
        for(String email: graph.keySet()){
            if(!visited.contains(email)){
                visited.add(email);
                List<String> list = new ArrayList<String>();
                dfs(graph, visited, list, email);
                Collections.sort(list);
                list.add(0, emailToName.get(email));
                lists.add(list);
            }
        }
        return lists;
    }
    
    public void dfs(HashMap<String, TreeSet<String>> graph, 
                   Set<String> visited, 
                   List<String> list,
                   String start){
        list.add(start);
        TreeSet<String> neighbors = graph.get(start);
        for(String neighbor : neighbors){
            if(!visited.contains(neighbor)){
                visited.add(neighbor);
                dfs(graph, visited, list, neighbor);
            }
        }
    }
}

思路3:同上面的思路2,DFS改成BFS;

Accounts Merge

class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        List<List<String>> lists = new ArrayList<List<String>>();
        if(accounts == null || accounts.size() ==0) return lists;
        
        // build graph
        HashMap<String, TreeSet<String>> graph = new HashMap<String, TreeSet<String>>();
        HashMap<String, String> emailToName = new HashMap<String, String>();
        for(List<String> account: accounts){
            String name = account.get(0);
            for(int i=1; i<account.size(); i++){
                String email = account.get(i);
                emailToName.put(email,name);
                graph.putIfAbsent(email, new TreeSet<String>());
                if(i!=1){
                    graph.get(account.get(i)).add(account.get(i-1));
                    graph.get(account.get(i-1)).add(account.get(i));
                }
            }
        }
        
        // bfs
        HashSet<String> visited = new HashSet<String>();
        for(String email: graph.keySet()){
            if(!visited.contains(email)){
                List<String> list = new ArrayList<String>();
                visited.add(email);
                bfs(graph, visited, list, email);
                Collections.sort(list);
                list.add(0,emailToName.get(email));
                lists.add(list);
            }
        }
        return lists;
    }
    
    public void bfs(HashMap<String, TreeSet<String>> graph,
                   HashSet<String> visited,
                   List<String> list,
                   String start) {
        Queue<String> queue = new LinkedList<String>();
        queue.add(start);
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            while(size>0){
                String node = queue.poll();
                list.add(node);
                size--;
                for(String neighbor: graph.get(node)){
                    if(!visited.contains(neighbor)){
                        visited.add(neighbor);
                        queue.add(neighbor);
                    }
                }
            }
        }
    }
}

 

相关文章: