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的子序列个数。
二.题目解答
首先我们想到的是打表求出累加数组,然后再去遍历求解,这种做法很简答,但是很耗时,代码如下
class Solution { public: int subarraySum(vector<int>& nums, int k) { vector<int> sums = nums; int cur = 0; //打表 for(int i = 1; i < nums.size(); i++) sums[i] = sums[i - 1] + nums[i]; //查找 cur = 0; for(int i = 0; i < nums.size(); i++) { if(sums[i] == k) cur++; for(int j = i - 1; j >= 0; j--) { if(sums[i] - sums[j] == k) cur++; } } return cur; } };
上述代码用了两重循环,因而是很耗时的,我们考虑能否降低循环次数?
想了半天没想到,找到网上一种无序表的方法,无序表建立在连续数组之和与其出现次数之间的映射上。
下图是我的解释
代码如下:
class Solution { public: int subarraySum(vector<int>& nums, int k) { int cur = 0; unordered_map<int,int> umap{{0,1}}; int sum = 0; for(int i = 0;i < nums.size();i++){ sum += nums[i]; cur += umap[sum - k]; ++umap[sum]; } return cur; } };