Skip to content

Commit bc5b546

Browse files
author
weiy
committed
subarray sum equals K medium
1 parent 20b0080 commit bc5b546

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Array/SubarraySumEqualsK.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
12+
思路:
13+
1. 直接用了暴力的搜索法,TLE。
14+
2. Discuss 里用的哈希 + 保留和的方式。
15+
具体的是:
16+
pre 一直累加。
17+
如果 pre - k 存在于保存的字典中,那么结果里加上这个次数即可。
18+
19+
这种方法可行。但暂时没搞明白具体的原理。
20+
21+
22+
测试地址:
23+
https://leetcode.com/problems/subarray-sum-equals-k/description/
24+
25+
"""
26+
class Solution(object):
27+
def subarraySum(self, nums, k):
28+
"""
29+
:type nums: List[int]
30+
:type k: int
31+
:rtype: int
32+
"""
33+
dicts = {0:1}
34+
35+
result = 0
36+
37+
pre_sum = 0
38+
39+
for i in nums:
40+
pre_sum += i
41+
42+
result += dicts.get(pre_sum-k, 0)
43+
44+
dicts[pre_sum] = dicts.get(pre_sum, 0) + 1
45+
46+
return result
47+

0 commit comments

Comments
 (0)