力扣-684 冗余连接

# 利用并查集
class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        n = len(edges)
        parent = list(range(n+1))

        def find(index):				# 找到当前节点index的父节点
            if parent[index]==index:
                return index
            else:
                return find(find(parent[index]))
        
        def union(index1, index2):		# 将两个节点连在同一个根节点上
            parent[find(index1)] = find(index2)

        for index1, index2 in edges:	# 判断两个节点是不是同一个根节点
            if find(index1) == find(index2):
                return [index1, index2]
            else:
                union(index1, index2)

参考:

https://leetcode-cn.com/problems/redundant-connection/solution/684-rong-yu-lian-jie-bing-cha-ji-ji-chu-eartc/
https://leetcode-cn.com/problems/redundant-connection/solution/rong-yu-lian-jie-by-leetcode-solution-pks2/

猜你喜欢

转载自blog.csdn.net/tailonh/article/details/113820240