首页 > 其他 > 详细

leetcode-685-冗余连接②

时间:2019-10-15 12:30:32      阅读:77      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 技术分享图片

 

 参考后提交:并查集:

技术分享图片

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-冗余连接②

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!