Skip to content

Commit c12edc0

Browse files
authored
Create gcd-sort-of-an-array.py
1 parent 5b9db8e commit c12edc0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Python/gcd-sort-of-an-array.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Time: O(n * α(n) + m * log(logm)) ~= O(n + m), m is the max of nums
2+
# Space: O(n)
3+
4+
import itertools
5+
6+
7+
class UnionFind(object): # Time: O(n * α(n)), Space: O(n)
8+
def __init__(self, n):
9+
self.set = range(n)
10+
self.rank = [0]*n
11+
12+
def find_set(self, x):
13+
stk = []
14+
while self.set[x] != x: # path compression
15+
stk.append(x)
16+
x = self.set[x]
17+
while stk:
18+
self.set[stk.pop()] = x
19+
return x
20+
21+
def union_set(self, x, y):
22+
x_root, y_root = map(self.find_set, (x, y))
23+
if x_root == y_root:
24+
return False
25+
if self.rank[x_root] < self.rank[y_root]: # union by rank
26+
self.set[x_root] = y_root
27+
elif self.rank[x_root] > self.rank[y_root]:
28+
self.set[y_root] = x_root
29+
else:
30+
self.set[y_root] = x_root
31+
self.rank[x_root] += 1
32+
return True
33+
34+
35+
class Solution(object):
36+
def gcdSort(self, nums):
37+
"""
38+
:type nums: List[int]
39+
:rtype: bool
40+
"""
41+
def modified_sieve_of_eratosthenes(n, lookup, uf): # Time: O(n * log(logn)), Space: O(n)
42+
if n < 2:
43+
return
44+
is_prime = [True]*(n+1)
45+
for i in xrange(2, len(is_prime)):
46+
if not is_prime[i]:
47+
continue
48+
for j in xrange(i+i, len(is_prime), i):
49+
is_prime[j] = False
50+
if j in lookup: # modified
51+
uf.union_set(i-1, j-1)
52+
53+
max_num = max(nums)
54+
uf = UnionFind(max_num)
55+
modified_sieve_of_eratosthenes(max_num, set(nums), uf)
56+
return all(uf.find_set(a-1) == uf.find_set(b-1) for a, b in itertools.izip(nums, sorted(nums)))

0 commit comments

Comments
 (0)