684. 冗余连接

Difficulty
Medium
Tags
并查集
Star
树可以看成是一个连通且 无环 无向 图。
给定往一棵 n 个节点 (节点值 1~n) 的树中添加一条边后的图。添加的边的两个顶点包含在 1n 中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n 的二维数组 edgesedges[i] = [ai, bi] 表示图中在 aibi 之间存在一条边。
请找出一条可以删去的边,删除后可使得剩余部分是一个有着 n 个节点的树。如果有多个答案,则返回数组 edges 中最后出现的边。
示例 1:
notion imagenotion image
输入: edges = [[1,2], [1,3], [2,3]] 输出: [2,3]
示例 2:
notion imagenotion image
输入: edges = [[1,2], [2,3], [3,4], [1,4], [1,5]] 输出: [1,4]
提示:
  • n == edges.length
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= ai < bi <= edges.length
  • ai != bi
  • edges 中无重复元素
  • 给定的图是连通的
通过次数64,862提交次数97,238

法 1 并查集

思路
挨个将每个edge中的两个节点 进行union, 如果某两个节点之前已经是在一个集合中了,那就说明当前这个 edge 是多余的。
题解
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: res = [] uf = Unionfind(len(edges)+1) for i in range(len(edges)): # 如果之前已经建立过链接了,那么就可以做为答案直接返回 if uf.find(edges[i][0]) == uf.find(edges[i][1]): return edges[i] uf.union(*edges[i]) # 并查集模板 class Unionfind: def __init__(self, n): self.parents = [i for i in range(n)] def find(self, x): if self.parents[x] != x: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): root_x = self.find(x) root_y = self.find(y) if root_x != root_y: self.parents[root_x] = root_y