1.Description
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].
解读
给定一个整数数组,和一个整数k,求有多少个连续子序列的和为k。
2.Solution
解题思路:
最能想到的办法就是遍历了,存储前n项的和,然后递减回去,但是超时了
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if nums == []: return 0
sumlist, N = [nums[0]], 0
for i in range(1, len(nums)):
sumlist.append(sumlist[-1] + nums[i])
for i in range(len(sumlist)):
if sumlist[i] == k:
N = N + 1
for j in range(i):
if sumlist[i] - sumlist[j] == k:
N = N + 1
#print(N)
return N
那么可以想到:通过记录前n项和的次数,来快速得到解,什么意思呢,
比如我们已经把前面n-1
项和的次数放入到了词典中,比如{
S1
:2,
S2
:3,
S3
:3 …
Si
:V…
Sn−1:k′
},这时候新来一个
Sn
, 如果
Sn
-K(题目中给的值:要求的和)=
Si
,恰好在上面次数词典中,我们就可以直接把次数V提取出来。
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
count,cur,res={0:1},0,0
for num in nums:
cur=cur+num#计算前n项和
# (如果前n项和)cur-(需要求的和)k in (前n项和次数)词典中,那么get出来次数
res=res+count.get(cur-k,0)
count[cur]=count.get(cur,0)+1 #(如果前n项和)cur(的次数)在字典中加1
return res