题目:
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].
思路:
首先还是建立一个map,从数组的累积和映射到索引上,这样我们就可以在O(1)的时间内求出任意子区间的和。然后试图以每个元素i为子区间的末尾,计算[0, j] (j < i)的区间和需要是多少,才能使得[j + 1, i]区间的和为k,然后就在map中查找。每找到一个,结果就加1,最后返回结果就可以了。由于不同的索引可能会对应同一个累积和,所以我们需要用multimap来实现。算法的时间复杂度是O(nlogn),空间复杂度是O(n)。
代码:
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
vector<int> sums(nums.size() + 1, 0);
multimap<int, int> mp; // {sum, index}
mp.insert(make_pair(0, 0));
for (int i = 1; i <= nums.size(); ++i) {
sums[i] = sums[i - 1] + nums[i - 1];
mp.insert(make_pair(sums[i], i));
}
int ans = 0;
for (int i = 1; i < sums.size(); ++i) {
int value = sums[i] - k;
auto ret = mp.equal_range(value);
for (auto it = ret.first; it != ret.second; ++it) {
if (it->second < i) {
++ans;
}
}
}
return ans;
}
};