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;
        }
    }
    
  • 相关阅读:
    设计模式入门
    Spring Boot 日志
    Spring Boot入门
    Vue--过滤器、指令、插件
    CentOS7更换yum源
    CentOS7中修改运行级别
    Xshell进行远程登录
    Linux的目录结构详情
    通过VMware Tools配置Centos7与本地主机的共享文件夹(亲测)
    eclipse中的Git操作
  • 原文地址:https://www.cnblogs.com/reboot329/p/5947859.html
Copyright © 2011-2022 走看看