560. Subarray Sum Equals K 题解
题目描述:
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].
题目链接:560. Subarray Sum Equals K
算法描述:
由题意知,给定一个整数数组及整数 k ,我们需要找到数组中和为 k 的连续的子数组的个数。
首先,我们构造 sum 容器,遍历原数组,将当前位置之前所有元素的和填入 sum 容器。
之后,我们再次遍历原数组,使用两个 for 循环求数组中的连续元素的和,其中如下代码所示,sum[j] - sum[i] 表示 j 与 i+1 之间元素的和,当它们的和为 k 时,结果加一。
代码:
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int ans = 0;
vector<int> sum(nums.size()+1, 0);
for(int i=0; i<nums.size(); i++){
sum[i+1] = sum[i] + nums[i];
}
for(int i=0; i<nums.size(); i++){
for(int j=i+1; j<nums.size()+1; j++){
if(sum[j] - sum[i] == k){
ans++;
}
}
}
return ans;
}
};