zoukankan      html  css  js  c++  java
  • 721.账户合并(并查集)

    https://leetcode-cn.com/problems/accounts-merge/

    这道题想了蛮久的 需要对邮箱进行字典序输出。

    大致过程如下

    import java.awt.image.AreaAveragingScaleFilter;
    import java.util.*;
    
    class Solution {
    
        int[] pre;
    
        public List<List<String>> accountsMerge(List<List<String>> accounts) {
            int size = accounts.size();
            pre = new int[size];
            for (int i = 0; i < size; i++)
                pre[i] = i;
            TreeMap<String, Integer> map1 = new TreeMap<>();
            HashMap<Integer, String> map2 = new HashMap<>();
            for (int i = 0; i < size; i++) {
                List<String> temp = accounts.get(i);
                map2.put(i, temp.get(0));
                for (int j = 1; j < temp.size(); j++) {
                    if (map1.containsKey(temp.get(j))) {
                        int ancestorX = find(map1.get(temp.get(j)));
                        int ancestorY = find(i);
                        pre[ancestorY] = ancestorX;
                    } else {
                        map1.put(temp.get(j), i);
                    }
                }
            }
            for (int i = 0; i < size; i++) {
                int ancestor = find(i);
                for (Map.Entry<String, Integer> entry : map1.entrySet()) {
                    if (entry.getValue() == i)
                        entry.setValue(ancestor);
                }
            }
            List<List<String>> ans = new ArrayList<>();
            HashSet<Integer> flagSet = new HashSet<>();
            for (int i = 0; i < size; i++) {
                int ancestor = find(i);
                if (flagSet.contains(ancestor)) {
                    continue;
                } else {
                    flagSet.add(ancestor);
                    List<String> temp = new ArrayList<>();
                    temp.add(map2.get(ancestor));
                    for (Map.Entry<String, Integer> entry : map1.entrySet()) {
                        if (entry.getValue() == ancestor)
                            temp.add(entry.getKey());
                    }
                    ans.add(temp);
                }
            }
            return ans;
        }
    
        int find(int x) {
            if (pre[x] == x) {
                return x;
            } else {
                int root = find(pre[x]);
                pre[x] = root;
                return pre[x];
            }
        }
    }
  • 相关阅读:
    Groovy Simple file download from URL
    Connect to URL and dump webpage in Groovy Stack Overflow
    bash脚本测网络流量
    HTTPBuilder Overview
    nginx设置代理账号密码
    引爆流行
    RRDtool About RRDtool
    老王 python ,
    Ubuntu下安装GeoIP
    实时查看网络的流量
  • 原文地址:https://www.cnblogs.com/yuanweidao/p/14294883.html
Copyright © 2011-2022 走看看