forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredundant-connection-ii.py
43 lines (36 loc) · 1.17 KB
/
redundant-connection-ii.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
# Time: O(nlog*n) ~= O(n), n is the length of the positions
# Space: O(n)
class UnionFind(object):
def __init__(self, n):
self.set = range(n)
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root == y_root:
return False
self.set[min(x_root, y_root)] = max(x_root, y_root)
return True
class Solution(object):
def findRedundantDirectedConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
cand1, cand2 = [], []
parent = {}
for edge in edges:
if edge[1] not in parent:
parent[edge[1]] = edge[0]
else:
cand1 = [parent[edge[1]], edge[1]]
cand2 = edge
union_find = UnionFind(len(edges)+1)
for edge in edges:
if edge == cand2:
continue
if not union_find.union_set(*edge):
return cand1 if cand2 else edge
return cand2