题目:
Given an array of integers and an integer
k
, you need to find the total number of continuous subarrays whose sum equals tok
.
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 integerk
is
[-1e7, 1e7]
.
解释:
求一个数组中和为k的subarray的个数。用hashmap存储某个元素之前(包括这个元素)的所有元素的和的个数(也就是在遍历的过程中需要更新hashmap),这样求和更方便。
1.解法1:暴力解法,计算sum(i,j),O(n2)的时间复杂度
2.解法2:基于解法1的暴力解法,主要思想是sum(i,j)=sum(0,j)-sum(0,i-1)
所以保存之前的和就好preSum是个字典,字典的key保存的是和,字典的val保存是这个和的个数,当前前项和为curSum
,那么和为curSum-k
的前项和的个数就是和为k
的子字符串的个数。时间复杂度是O(n),空间复杂度也是O(n)。
python代码:
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
preSumCount={}
curSum=0
result=0
preSumCount[0]=1
for num in nums:
curSum+=num
if curSum-k in preSumCount:
result+=preSumCount[curSum-k]
preSumCount[curSum]=preSumCount.get(curSum,0)+1
return result
c++代码:
#include<map>
using namespace std;
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
map<int,int>preSumCount;
//这个初始化很重要
preSumCount[0]=1;
int preSum=0;
int result=0;
for(auto num:nums)
{
preSum+=num;
result+=preSumCount[preSum-k];
preSumCount[preSum]+=1;
}
return result;
}
};
总结:
本题的主要思想是sum(i,j)=sum(0,j)-sum(0,i-1),这种思想在很多子字符串求和的地方可以运用,和字典一起使用,可以大大减少求和速度。