1. 问题描述
给定一个整数数组和一个整数k,你需要找到连续子数列的和为k的总个数。
2. 样例
样例1
输入: nums = [1,1,1] 和 k = 2
输出: 2
解释:
子数组 [0,1] 和 [1,2]
样例2
输入: nums = [2,1,-1,1,2] 和 k = 3
输出: 4
解释:
子数组 [0,1], [1,4], [0,3] and [3,4]
3. 代码
方法一: 暴力枚举 但是使用Python方法会超时
class Solution:
"""
@param nums: a list of integer
@param k: an integer
@return: return an integer, denote the number of continuous subarrays whose sum equals to k
"""
def subarraySumEqualsK(self, nums, k):
# write your code here
count = 0
for i in range(len(nums)):
sub = 0
for j in range(i, len(nums)):
sub += nums[j]
if sub == k:
count+=1
return count
方法二:
利用字典存储值。 加上新数 - k = 出现过的和 -> 加上新数 - 出现过的和 = k
class Solution:
"""
@param nums: a list of integer
@param k: an integer
@return: return an integer, denote the number of continuous subarrays whose sum equals to k
"""
def subarraySumEqualsK(self, nums, k):
# write your code here
count=0
dic={0:1}
sub=0
for i in range(len(nums)):
sub+=nums[i]
if (sub-k) in dic:
count+=dic[sub-k]
if sub not in dic:
dic[sub]=1
else:
dic[sub]+=1
return count