码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-685-冗余连接②

时间:2019-10-15 13:34:47      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:cte   alt   冗余   self   src   lis   gre   ant   mamicode   

题目描述:

技术图片

 

 技术图片

 

 参考后提交:并查集:

技术图片

class Solution:
    def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
        def find(f,x):
            f.setdefault(x,x)
            if f[x] != x:
                f[x] = find(f,f[x])
            return f[x]
        def cycle(graph):
            f = {}
            for x,y in graph:
                if find(f,x) == find(f,y):
                    return True
                else:
                    f[find(f,y)] = find(f,x)
        indegree = {i:0 for i in range(1,len(edges)+1)}
        tmp = 0
        for i,j in edges:
            indegree[j] += 1
            if indegree[j] == 2:
                tmp = j
                break
        if tmp == 0:
            f = {}
            for x,y in edges:
                if find(f,x) == find(f,y):
                    return [x,y]
                else:
                    f[find(f,y)] = find(f,x)
        else:
            for x,y in edges[::-1]:
                if y == tmp:
                    if not cycle(edges[:edges.index([x,y])]+edges[edges.index([x,y])+1:]) :
                        return [x,y]
        

 

leetcode-685-冗余连接②

标签:cte   alt   冗余   self   src   lis   gre   ant   mamicode   

原文地址:https://www.cnblogs.com/oldby/p/11676786.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!