leetcode-684-冗余连接

题目描述:

 

 

 

 方法一:dfs()  O(N**2)

from collections import defaultdict
class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        d = defaultdict(list)
        for i,j in edges:
            d[i] += [j]
            d[j] += [i]
        res = []
        def dfs(u,v,visited):
            if v not in visited:
                visited.add(v)
                for i in d[v] :
                    if i == u:
                        continue
                    dfs(v,i,visited)
            else:
                res.append([u,v])
                return
        for u,v in edges:
            visited = set()
            dfs(u,v,visited)
        for i,j in edges[::-1]:
            if [i,j] in res :
                return [i,j]

 

方法二:并查集 O(N) O(N)

from collections import defaultdict
class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        f = {}
        def find(x):
            f.setdefault(x,x)
            if f[x] != x:
                f[x] = find(f[x])
            return f[x]
        def union(x,y):
            if find(x) != find(y):
                f[find(y)] = find(x)
        for x,y in edges:
            if find(x) == find(y):
                return [x,y]
            else:
                union(x,y)
            

另:

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        p = {i: {i} for i in range(1, len(edges) + 1)}  #并查集初始化
        for x, y in edges:
            if p[x] is not p[y]:    #如果两个集合地址不一样
                p[x] |= p[y]        #合并集合
                for z in p[y]:
                    p[z] = p[x]     #修改元素集合标记的指针地址
            else:
                return [x, y]

 

posted @ 2019-10-15 09:52  oldby  阅读(287)  评论(0编辑  收藏  举报