Given an integer array nums and an integer k, return the total number of contiguous subarrays whose sum equals k.
A subarray is a contiguous non-empty sequence of elements within the array. The array may contain negative numbers and zeros.
0 <= nums.length <= 2 * 10^4-10^4 <= nums[i] <= 10^4-10^9 <= k <= 10^9Example 1:
Input: nums = [1,1,1], k = 2 Output: 2
Explanation:
The subarrays [1, 1] and [1, 1] both have a sum equal to k.
Example 2:
Input: nums = [1,2,3], k = 3 Output: 2
Explanation:
The subarrays [1, 2] and [3] both have a sum equal to k.
To solve this problem, you can use a hash map to store the cumulative sum of the array and its index. For each element in the array, calculate the difference between the current cumulative sum and k. If this difference has been seen before, it means there is a subarray ending at the current index with a sum of k. Increment the count by the number of times this difference has been seen before.