-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.py
43 lines (38 loc) · 1.32 KB
/
Solution2.py
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
class UnionFind:
__slots__ = "p", "size"
def __init__(self, n: int):
self.p: List[int] = list(range(n))
self.size: List[int] = [1] * n
def find(self, x: int) -> int:
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a: int, b: int) -> bool:
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
class Solution:
def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
n = len(edges)
ind = [0] * n
for _, v in edges:
ind[v - 1] += 1
dup = [i for i, (_, v) in enumerate(edges) if ind[v - 1] == 2]
uf = UnionFind(n)
if dup:
for i, (u, v) in enumerate(edges):
if i == dup[1]:
continue
if not uf.union(u - 1, v - 1):
return edges[dup[0]]
return edges[dup[1]]
for i, (u, v) in enumerate(edges):
if not uf.union(u - 1, v - 1):
return edges[i]