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].
Solution:
The idea is to use a HashMap to store the prefixSum and its frequency.
When we are at index i with prefixSum sum, we check if there exists a prefixSum (sum - k).
If so, the frequency of this (sum - k) means how many different continuous subarray we can have that end with i will sum up to k.
The time complexity is O(n) and the space complexity is also O(n).
Code:
public class Solution { public int subarraySum(int[] nums, int k) { if (nums == null || nums.length == 0) { return 0; } int count = 0; HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 1); int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (map.containsKey(sum - k)) { count += map.get(sum - k); } if (!map.containsKey(sum)) { map.put(sum, 1); } else { map.put(sum, map.get(sum) + 1); } } return count; } }