-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0684-redundant-connection.rs
60 lines (51 loc) · 1.36 KB
/
0684-redundant-connection.rs
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::cmp::Ordering;
struct UnionFind {
parent: Vec<usize>,
rank: Vec<i32>,
}
impl UnionFind {
fn new(n: usize) -> Self {
UnionFind {
parent: (0..(n + 1)).collect(),
rank: vec![1; n + 1],
}
}
fn find(&mut self, n: usize) -> usize {
let mut p = self.parent[n];
while p != self.parent[p] {
self.parent[p] = self.parent[self.parent[p]];
p = self.parent[p];
}
p
}
fn union(&mut self, n1: usize, n2: usize) -> bool {
let p1 = self.find(n1);
let p2 = self.find(n2);
if p1 == p2 {
return false;
}
match self.rank[p1].cmp(&self.rank[p2]) {
Ordering::Greater => {
self.parent[p2] = p1;
self.rank[p1] += self.rank[p2];
}
_ => {
self.parent[p1] = p2;
self.rank[p2] = self.rank[p1];
}
}
true
}
}
impl Solution {
pub fn find_redundant_connection(edges: Vec<Vec<i32>>) -> Vec<i32> {
let mut union_find = UnionFind::new(edges.len() + 1);
for edge in edges {
let (n1, n2) = (edge[0] as usize, edge[1] as usize);
if !union_find.union(n1, n2) {
return vec![n1 as i32, n2 as i32];
}
}
unreachable!()
}
}