forked from HuberTRoy/leetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubarraySumEqualsK.py
47 lines (33 loc) · 1.14 KB
/
SubarraySumEqualsK.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
"""
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
思路:
1. 直接用了暴力的搜索法,TLE。
2. Discuss 里用的哈希 + 保留和的方式。
具体的是:
pre 一直累加。
如果 pre - k 存在于保存的字典中,那么结果里加上这个次数即可。
这种方法可行。但暂时没搞明白具体的原理。
测试地址:
https://leetcode.com/problems/subarray-sum-equals-k/description/
"""
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dicts = {0:1}
result = 0
pre_sum = 0
for i in nums:
pre_sum += i
result += dicts.get(pre_sum-k, 0)
dicts[pre_sum] = dicts.get(pre_sum, 0) + 1
return result