-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
largest-component-size-by-common-factor.py
110 lines (93 loc) · 3.28 KB
/
largest-component-size-by-common-factor.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# Time: O(f * n), f is the max number of unique prime factors
# Space: O(p + n), p is the total number of unique primes
import collections
class UnionFind(object):
def __init__(self, n):
self.set = range(n)
self.size = [1]*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)
self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]
return True
class Solution(object):
def largestComponentSize(self, A):
"""
:type A: List[int]
:rtype: int
"""
def prime_factors(i): # prime factor decomposition
result = []
d = 2
if i%d == 0:
while i%d == 0:
i //= d
result.append(d)
d = 3
while d*d <= i:
if i%d == 0:
while i%d == 0:
i //= d
result.append(d)
d += 2
if i != 1:
result.append(i)
return result
union_find = UnionFind(len(A))
nodesWithCommonFactor = collections.defaultdict(int)
for i in xrange(len(A)):
for factor in prime_factors(A[i]):
if factor not in nodesWithCommonFactor:
nodesWithCommonFactor[factor] = i
union_find.union_set(nodesWithCommonFactor[factor], i)
return max(union_find.size)
# Time: O(f * n), f is the max number of unique prime factors
# Space: O(p + n), p is the total number of unique primes
import collections
class UnionFind(object):
def __init__(self, n):
self.set = range(n)
self.size = [1]*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)
self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]
return True
class Solution2(object):
def largestComponentSize(self, A):
"""
:type A: List[int]
:rtype: int
"""
def prime_factors(x): # prime factor decomposition
result = []
p = 2
while p*p <= x:
if x%p == 0:
while x%p == 0:
x //= p
result.append(p)
p += 1
if x != 1:
result.append(x)
return result
union_find = UnionFind(len(A))
nodesWithCommonFactor = collections.defaultdict(int)
for i in xrange(len(A)):
for factor in prime_factors(A[i]):
if factor not in nodesWithCommonFactor:
nodesWithCommonFactor[factor] = i
union_find.union_set(nodesWithCommonFactor[factor], i)
return max(union_find.size)