题目描述:

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

方法二:并查集 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]
02-12 03:19