Skip to content

Commit 6995fb7

Browse files
committedApr 14, 2020
O(n) time and O(n) space using Hashtable.
1 parent ed59d2f commit 6995fb7

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
 
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
3+
4+
Example 1:
5+
Input:nums = [1,1,1], k = 2
6+
Output: 2
7+
Note:
8+
The length of the array is in range [1, 20,000].
9+
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
10+
"""
11+
class Solution:
12+
def subarraySum(self, nums: List[int], k: int) -> int:
13+
result,total,hmap = 0,0,{}
14+
for num in nums:
15+
hmap[total] = hmap.get(total,0) + 1
16+
total += num
17+
if hmap.get(total-k):
18+
result += hmap[total-k]
19+
return result

0 commit comments

Comments
 (0)
Please sign in to comment.