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

    Minimum Height Trees

    要点:这题实质是topological sort。重点是这是对无向图,和有向图的几点区别:

    • 不需要indegree,因为无向图入度和出度是相同的,所以邻接点的个数就能表示。下一层某结点只需要从adjSet中删除当前层结点即可
    • 因为至少有degree 1,所以要这个是下一层的选择条件
    class Solution(object):
        def findMinHeightTrees(self, n, edges):
            """
            :type n: int
            :type edges: List[List[int]]
            :rtype: List[int]
            """
            adjList = [set() for i in range(n)]
            for e in edges:
                adjList[e[0]].add(e[1])
                adjList[e[1]].add(e[0])
                
            q = []
            for i in range(len(adjList)):
                if len(adjList[i])==1 or len(adjList[i])==0:
                    q.append(i)
    
            while q:
                qnext = []
                for i in range(len(q)):
                    for e in adjList[q[i]]:
                        adjList[e].remove(q[i])
                        if len(adjList[e])==1:
                            qnext.append(e)
                            
                if not qnext: return q
                q=qnext
            return []
                    
    
  • 相关阅读:
    开发中的报错问题
    vue2.0入门
    nodejs的一些基操
    git
    es6模块化规范
    js面向对象的笼统介绍
    this指向问题(改变它的指向)
    js面向对象杂谈
    原生js贪吃蛇
    bootstrap基础自我总结
  • 原文地址:https://www.cnblogs.com/absolute/p/5678133.html
Copyright © 2011-2022 走看看