zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 94

    Number of Connected Components in an Undirected Graph

    要点:
    union-find如何记?

    • data structure就一个array/list,每个元素初始化为val=index,表示每个元素是独立的。之后还保持的元素一定是union后的根。
    • union的过程先find(O(lgn)),然后选rank小的合并。
    • 这里可以简化,不记录rank,任意合并,code可以简化不少

    错误点:

    • find:recursion的arg是parents[x],不是x(否则成死循环了)
    • xrange doesn’t support item assignment, use range instead

    https://repl.it/Cbe0/1

    
    # Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
    
    # Example 1:
    #      0          3
    #      |          |
    #      1 --- 2    4
    # Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.
    
    # Example 2:
    #      0           4
    #      |           |
    #      1 --- 2 --- 3
    # Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.
    
    # Note:
    # You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
    
    
    class Solution(object):
        def countComponents(self, n, edges):
            """
            :type n: int
            :type edges: List[List[int]]
            :rtype: int
            """
            p = range(n)
            def find(x):
            	if p[x]!=x:
            		p[x]=find(p[x])
            	return p[x]
            
            for s,d in edges:
            	ss, dd = find(s),find(d) 
            	p[ss] = dd
            	n-=ss!=dd
            return n
    
    sol = Solution()
    assert sol.countComponents(5, [[0,1],[1,2],[3,4]])==2, "should be 2"
    assert sol.countComponents(5, [[0,1],[1,2],[0,2],[3,4]])==2, "should be 2"
            
    
  • 相关阅读:
    金山词霸注册表怎么删
    新手学习jquery
    《企业应用架构模式》(POEAA)读书笔记
    Silverlight 4 tools
    asp.net非常基础的面试题
    VS 2010 中文版正式版无法安装Silverlight4 Tools的解决办法
    OnPreRender(EventArgs e) 事件常用的方法
    各大搜索引擎网站登录入口
    向用户控件传递参数的问题
    URLRewriter
  • 原文地址:https://www.cnblogs.com/absolute/p/5815848.html
Copyright © 2011-2022 走看看