zoukankan      html  css  js  c++  java
  • leetcode721


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

    Union Find.
    1.初始化Union find。用accounts里面的下标作为id标注原始的一条条。
    2.遍历accounts, 用一个数据结构Map<String, List<Integer>> 存储email -> ids的映射信息。让共享同一个email的不同行聚集到一个set里。(用List是因为之后Union find需要下标信息,而set没下标)
    3.遍历刚才产生的emailToId,union find一下同一个list里的不同id,现在的father就是他们的共享realId
    4.再遍历一次accounts,用一个数据结构Map<Integer, Set<String>>存储初步结果,也就是ids -> emails的信息。用Map的原因是你不知道有多少个realId。用Set的原因是把之前好几个相同的email压成一个去重。
    5.再遍历刚才产生的idToEmail,把结果转化为题目想要的样子List<List<String>>。生成list, sort,最前面插名字。

    实现:

    class Solution {
        private int[] father;
        
        public List<List<String>> accountsMerge(List<List<String>> accounts) {
            List<List<String>> ans = new ArrayList<>();
            if (accounts == null || accounts.size() == 0) {
                return ans;
            }
            
            this.father = new int[accounts.size()];
            for (int i = 0; i < father.length; i++) {
                father[i] = i;
            }
            
            Map<String, List<Integer>> emailToId = generateEmailToId(accounts);
            for (List<Integer> sameIds : emailToId.values()) {
                for (int i = 1; i < sameIds.size(); i++) {
                    Union(sameIds.get(i), sameIds.get(0));
                }
            }
            
            Map<Integer, Set<String>> idToEmail = generateIdToEmail(accounts);
            for (int id : idToEmail.keySet()) {
                List<String> emails = new ArrayList<>(idToEmail.get(id));
                Collections.sort(emails);
                emails.add(0, accounts.get(id).get(0));
                ans.add(emails);
            }
            return ans;
            
        }
        
        private Map<String, List<Integer>> generateEmailToId(List<List<String>> accounts) {
            Map<String, List<Integer>> ans = new HashMap<>();
            for (int id = 0; id < accounts.size(); id++) {
                List<String> emails = accounts.get(id);
                for (int i = 1; i < emails.size(); i++) {
                    List<Integer> list = ans.getOrDefault(emails.get(i), new ArrayList<Integer>());
                    list.add(id);
                    ans.put(emails.get(i), list);
                }
            }
            return ans;
        }
        
        private Map<Integer, Set<String>> generateIdToEmail(List<List<String>> accounts) {
            Map<Integer, Set<String>> ans = new HashMap<>();
            for (int id = 0; id < accounts.size(); id++) {
                List<String> emails = accounts.get(id);
                int realId = find(id);
                Set<String> set = ans.getOrDefault(realId, new HashSet<String>());
                for (int i = 1; i < emails.size(); i++) {
                    set.add(emails.get(i));
                }
                ans.put(realId, set);
            }
            return ans;
        }
        
        private void Union(int a, int b) {
            int fatherA = find(a);
            int fatherB = find(b);
            if (fatherA != fatherB) {
                father[fatherB] = fatherA;
            }
        }
    
        private int find(int a) {
            if (father[a] == a) {
                return a;
            }
            return father[a] = find(father[a]);
        }
    }
  • 相关阅读:
    在文本框按回车 表单自动提交的解决方法
    类型提示保障数据安全
    LastModified,ETag,CacheControl,Expires 设置页面过期策略
    Netstat 状态分析
    Web 开发与设计师速查手册大全(上)
    Google推出网页加速工具Page Speed
    最近关于twitter架构的一篇文章
    PHP cookie和session的分析(转)
    关于win10深度学习安装配置 CUDA9.0+VS2017+Cudnn7.4.1.5+Anaconda3(cupy安装包)+python3.7+pycharm
    Python命令行解析argparse常用语法使用简介
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9668399.html
Copyright © 2011-2022 走看看