leetcode
使用并查集方法,维护联通分量数组,检验每条边的两个节点,如果已经联通了,则当前边导致成环,为冗余链接。
时间复杂度:
空间复杂度:O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| func findRedundantConnection(edges [][]int) []int { group := make([]int, len(edges) + 1) for i := 0; i < len(edges) + 1; i++ { group[i] = i }
var find func(i int) int
find = func(i int) int { if group[i] == i { return i }
return find(group[i]) }
union := func(from int, to int) bool { from = find(from) to = find(to)
if from == to { return true }
group[to] = from return false }
for _, edge := range edges { if union(edge[0], edge[1]) { return edge } }
return []int{} }
|