题目描述:
给你一个整数数组 nums
和一个整数 k
,请你统计并返回 该数组中和为 k
的子数组的个数 。
子数组是数组中元素的连续非空序列。
示例:
输入:nums = [1,1,1], k = 2 输出:2
基本思路:
前缀和:pre[i] = num[0] + nums[1] + ... + nums[i]
前缀和+hash表优化:将这个数组中前面的所有数相加得到前缀和,并存储到hash<前缀和,出现的次数>,并对hash表中每个数组进行pre-k看是否存在于hash表中,若存在,则总数+1.
for(auto& x:nums) 迭代容器中的所有元素,用x作为临时变量
=for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)
!=mp.end() 不等于迭代器的尾的迭代器
代码运行:
#include<iostream>
#include<map>
#include<unordered_map>
using namespace std;
class Solution{
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int>mp;
int pre=0,count=0;
mp[0]=1
for(auto &x:nums){
pre+=x;
if(mp.find(pre-k)!=mp.end()){
count+=mp[pre-k];
}
mp[pre]++;
}
return count;
}
};