1. Title
Given an array of integers and an integer k, you need to find the number of consecutive subarrays in the array whose sum is k .
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/subarray-sum-equals-k The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
2. Problem solving
Similar topics: LeetCode 1248. Statistics "beautiful sub-array" (to be reviewed)
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> m;//和,数组个数
int i, sum = 0, count = 0;
m[0] = 1;//边界,和为0的子数组数量为1
for(i = 0; i < nums.size(); ++i)
{
sum += nums[i];
// m[sum]++;不能写在这
count += m[sum-k];
m[sum]++;
}
return count;
}
};
96 ms 21.2 MB