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];
        }
    }
}

 

posted @ 2021-01-18 20:06  缘未到  阅读(81)  评论(0编辑  收藏  举报