Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals to k
.
Example 1:
Input: nums = [1,1,1], k = 2 Output: 2
Example 2:
Input: nums = [1,2,3], k = 3 Output: 2
Constraints:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
Companies:
Facebook, Amazon, Google, Oracle, ByteDance, Quora, tiktok, Microsoft, LinkedIn, Bloomberg, Apple, Snapchat, Expedia, Walmart Labs, Tesla, Paypal, Visa, DoorDash
Related Topics:
Array, Hash Table, Prefix Sum
Similar Questions:
- Two Sum (Easy)
- Continuous Subarray Sum (Medium)
- Subarray Product Less Than K (Medium)
- Find Pivot Index (Easy)
- Subarray Sums Divisible by K (Medium)
- Minimum Operations to Reduce X to Zero (Medium)
- K Radius Subarray Averages (Medium)
// OJ: https://leetcode.com/problems/subarray-sum-equals-k/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int ans = 0, sum = 0;
unordered_map<int, int> m{{0, 1}};
for (int n : nums) {
sum += n;
auto it = m.find(sum - k);
if (it != m.end()) ans += it->second;
m[sum]++;
}
return ans;
}
};