zoukankan      html  css  js  c++  java
  • 323. Number of Connected Components in an Undirected Graph

    May-26-2019

    UF做算是白给的
    压缩下,没Quick union(否则要几把weight),然后比较integer用equals稳点= =顺便尽量别int[]能MAP最好MAP

    class Solution {
        
        public class UF {
            Map<Integer, Integer> roots;
            Map<Integer, Integer> size;
            int num;
            public UF(int n) {
                roots = new HashMap<>();
                size = new HashMap<>();
                num = n;
                for (int i = 0; i < n; i ++) {
                    roots.put(i, i);
                    size.put(i, 1);
                }
            }
            
            public Integer find(Integer n) {
                if (!roots.containsKey(n)) return null;
                Integer root = n;
                while (!root.equals(roots.get(root))) {
                    roots.put(root, roots.get(roots.get(root)));
                    root = roots.get(root);
                }
                return root;
            }
            
            public void union(Integer a, Integer b) {
                Integer rootA = find(a);
                Integer rootB = find(b);
                
                if (rootA == null || rootB == null || rootA.equals(rootB)) return;
                
                Integer sizeA = size.get(rootA);
                Integer sizeB = size.get(rootB);
                if (sizeA > sizeB) {
                    roots.put(rootB, rootA);
                    size.put(rootA, sizeB + sizeA);
                } else {
                    roots.put(rootA, rootB);
                    size.put(rootB, sizeA + sizeB);
                }
                this.num --;
            }
            
        }
        public int countComponents(int n, int[][] edges) {
            if (edges.length == 0 || edges[0].length == 0) return n;
            
            UF uf = new UF(n);
            for (int[] edge : edges) {
                Integer a = edge[0];
                Integer b = edge[1];
                uf.union(a, b);
            }
            return uf.num;
        }
    }
    
  • 相关阅读:
    HDOJ_就这么个烂题总是WA先放这把
    [NYLG-OJ] 77 开灯问题(白书例题)
    [NEUQ-OJ] 1012 SZ斐波拉契数列
    福尔摩斯到某古堡探险
    第n个素数是多少?
    自然数的和之和
    水仙花数
    解决满屏显示问题的css样式:object-fit
    H5新属性audio音频和 video视频的控制
    用indexOf方法来去重
  • 原文地址:https://www.cnblogs.com/reboot329/p/5947859.html
Copyright © 2011-2022 走看看