forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-subarrays-with-gcd-equal-to-k.py
53 lines (48 loc) · 1.18 KB
/
number-of-subarrays-with-gcd-equal-to-k.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
# Time: O(nlogr), r = max(nums)
# Space: O(logr)
# dp
class Solution(object):
def subarrayGCD(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
result = 0
dp = collections.Counter()
for x in nums:
new_dp = collections.Counter()
if x%k == 0:
dp[x] += 1
for g, cnt in dp.iteritems():
new_dp[gcd(g, x)] += cnt
dp = new_dp
result += dp[k]
return result
# Time: O(n^2)
# Space: O(1)
# brute force
class Solution2(object):
def subarrayGCD(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
result = 0
for i in xrange(len(nums)):
g = 0
for j in xrange(i, len(nums)):
if nums[j]%k:
break
g = gcd(g, nums[j])
result += int(g == k)
return result