Problem
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarray-sum-equals-k
Method One:枚举
本来以为必定超时然后WA,竟然AC了hhhhh
Java
class Solution {
public int subarraySum(int[] nums, int k) {
int ans = 0;
int size = nums.length;
for (int i = 0; i < size; i++) {
int sum = 0;
for (int j = i; j < size; j++) {
sum += nums[j];
if (sum==k) ans++;
}
}
return ans;
}
}
Method Two:前缀和
这种方法我在做的时候只有一点点思路,具体怎么做并没有想到。
思路是这样的:遍历元素至i
。pre
为目前所有数字的和。如果子数组[t...i]
的和为n
,且n==k
(k为目标数字),则当pre-n==m
的情况存在,即存在t
个子数组[0...t]
的和为m
时,解的数量加t
。
C++
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
// 计数菌
int ans = 0;
// 前缀和
int pre = 0;
// 表示:子数组的和为key的情况有val种
map<int, int>mp;
mp[0] = 1;
for (auto x : nums) {
// 更新前缀和
pre += x;
// 即思路中提到的情况。存在mp[key]个子数组和为pre-k
if (mp.find(pre-k)!=mp.end()) ans += mp[pre-k];
// 更新存储
mp[pre]++;
}
return ans;
}
};