-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.go
39 lines (35 loc) · 906 Bytes
/
solution.go
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 {
parent := make([]int, len(edges)+1)
rank := make([]int, len(edges)+1)
for i := range parent {
parent[i] = i
}
var find func(int) int
find = func(node int) int {
if parent[node] != node {
parent[node] = find(parent[node])
}
return parent[node]
}
union := func(u, v int) bool {
rootU, rootV := find(u), find(v)
if rootU == rootV {
return false
}
if rank[rootU] > rank[rootV] {
parent[rootV] = rootU
} else if rank[rootU] < rank[rootV] {
parent[rootU] = rootV
} else {
parent[rootV] = rootU
rank[rootU]++
}
return true
}
for _, edge := range edges {
if !union(edge[0], edge[1]) {
return edge
}
}
return nil
}