-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path560_Subarray_Sum_Equals_K.py
71 lines (56 loc) · 1.65 KB
/
560_Subarray_Sum_Equals_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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from collections import defaultdict
class Solution(object):
# # Time:O(N), SpaceO(N)
# def subarraySum(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: int
# """
# result = 0
# currentSum = 0
# prefixSums = {0:1}
# for n in nums:
# currentSum += n
# difference = currentSum - k
# result += prefixSums.get(difference, 0)
# prefixSums[currentSum] = 1 + prefixSums.get(currentSum, 0)
# return result
# Time: O(N), Space: O(N)
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
prevSum = defaultdict(int)
result = 0
currentSum = 0
for i in range(0,len(nums)):
currentSum += nums[i]
if currentSum == k:
result += 1
if currentSum - k in prevSum:
result += prevSum[currentSum - k]
prevSum[currentSum] += 1
return result
def continuousSum(a, t):
if len(a) == 0:
return False
i = 0
tSum = 0
start = 0
while i < len(a):
if (tSum + a[i]) < t:
tSum += a[i]
elif (tSum + a[i]) == t:
return True
else:
tSum += a[i]
while tSum > t:
tSum -= a[start]
start += 1
if tSum == t:
return True
i += 1
return False