Description
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].
分析
题目的意思是:找出一个数组里面连续子数组的和为K的子数组的个数。
- 用一个map存起来,mp[0]的初始值为1,用于然后mp记录的是前m项的求和,mp[sum-k]如果为1,表明存在一个连续子序列的值为k,这需要找个test case模拟一下就行了。
C++
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int sum=0;
map<int,int> mp;
int count=0;
mp[0]++;
for(int i=0;i<nums.size();i++){
sum+=nums[i];
count+=mp[sum-k];
mp[sum]++;
}
return count;
}
};
Python
这道题重在理解,实现比较简单,然而居然翻车了,看来还需要多做几遍代码题,直到记住。
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
m_sum = defaultdict(int)
# 初始前缀和为0的出现次数为1
m_sum[0]=1
sum_num=0
res = 0
for i in range(len(nums)):
sum_num+=nums[i]
res+=m_sum[sum_num-k]
m_sum[sum_num]+=1
return res
参考文献
LeetCode Subarray Sum Equals K 子数组和为K
560. Subarray Sum Equals K