Skip to content

Commit 8bf3adc

Browse files
committed
Create P113. 和为K的子数组.md
1 parent 0a7b7c6 commit 8bf3adc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

P113. 和为K的子数组.md

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
***给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。输入:nums = [1,1,1], k = 2 输出: 2 , [1,1][1,1] 为两种不同的情况。***
2+
3+
```
4+
class Solution(object):
5+
def subarraySum(self, nums, k):
6+
"""
7+
:type nums: List[int]
8+
:type k: int
9+
:rtype: int
10+
"""
11+
#前缀和
12+
dic = {0:1}
13+
presum = 0
14+
count = 0
15+
for i in nums:
16+
presum += i
17+
count += dic.get(presum-k, 0)
18+
19+
if presum in dic:
20+
dic[presum] += 1
21+
else:
22+
dic[presum] = 1
23+
return count
24+
```

0 commit comments

Comments
 (0)