@@ -29,7 +29,7 @@ def largestComponentSize(self, A):
29
29
:type A: List[int]
30
30
:rtype: int
31
31
"""
32
- def primeFactors (i ): # prime factor decomposition
32
+ def prime_factors (i ): # prime factor decomposition
33
33
result = []
34
34
d = 2
35
35
if i % d == 0 :
@@ -43,14 +43,67 @@ def primeFactors(i): # prime factor decomposition
43
43
i //= d
44
44
result .append (d )
45
45
d += 2
46
- if i > 2 :
46
+ if i != 1 :
47
47
result .append (i )
48
48
return result
49
49
50
50
union_find = UnionFind (len (A ))
51
51
nodesWithCommonFactor = collections .defaultdict (int )
52
52
for i in xrange (len (A )):
53
- for factor in primeFactors (A [i ]):
53
+ for factor in prime_factors (A [i ]):
54
+ if factor not in nodesWithCommonFactor :
55
+ nodesWithCommonFactor [factor ] = i
56
+ union_find .union_set (nodesWithCommonFactor [factor ], i )
57
+ return max (union_find .size )
58
+
59
+
60
+ # Time: O(f * n), f is the max number of unique prime factors
61
+ # Space: O(p + n), p is the total number of unique primes
62
+ import collections
63
+
64
+
65
+ class UnionFind (object ):
66
+ def __init__ (self , n ):
67
+ self .set = range (n )
68
+ self .size = [1 ]* n
69
+
70
+ def find_set (self , x ):
71
+ if self .set [x ] != x :
72
+ self .set [x ] = self .find_set (self .set [x ]) # path compression.
73
+ return self .set [x ]
74
+
75
+ def union_set (self , x , y ):
76
+ x_root , y_root = map (self .find_set , (x , y ))
77
+ if x_root == y_root :
78
+ return False
79
+ self .set [min (x_root , y_root )] = max (x_root , y_root )
80
+ self .size [max (x_root , y_root )] += self .size [min (x_root , y_root )]
81
+ return True
82
+
83
+
84
+ class Solution2 (object ):
85
+ def largestComponentSize (self , A ):
86
+ """
87
+ :type A: List[int]
88
+ :rtype: int
89
+ """
90
+ def prime_factors (x ): # prime factor decomposition
91
+ result = []
92
+ p = 2
93
+ while p * p <= x :
94
+ if x % p == 0 :
95
+ while x % p == 0 :
96
+ x //= p
97
+ result .append (p )
98
+ p += 1
99
+ if x != 1 :
100
+ result .append (x )
101
+ return result
102
+
103
+ union_find = UnionFind (len (A ))
104
+ nodesWithCommonFactor = collections .defaultdict (int )
105
+ for i in xrange (len (A )):
106
+ for factor in prime_factors (A [i ]):
54
107
if factor not in nodesWithCommonFactor :
55
108
nodesWithCommonFactor [factor ] = i
56
109
union_find .union_set (nodesWithCommonFactor [factor ], i )
0 commit comments