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].
Idea – 1
Try all of the possible
[code lang="java"]
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int n = nums.length;
for(int i = 0; i < n; ++i)
{
int sum = 0;
for(int j = i; j < n; ++j)
{
sum += nums[j];
if(sum==k)
{
++count;
}
}
}
return count;
}
}
[code]
Runtime: 117 ms, faster than 28.52% of Java online submissions for Subarray Sum Equals K.Memory Usage: 38.2 MB, less than 95.55% of Java online submissions for Subarray Sum Equals K.
Idea – 2
If we needed to find two numbers that sum to K, we would be using a hash table. In a similar spirit, the problem could be thought of as finding two cumsums whose difference is k. Therefore if we have two indices p and q (p < q) and
[code lang="java"]
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
// Cumsum(0..j) == K case
map.put(0, 1);
// cumulative sum
int cumsum = 0;
for(int x : nums)
{
cumsum += x;
int delta = cumsum-k;
count += map.getOrDefault(delta, 0);
map.put( cumsum, map.getOrDefault(cumsum, 0)+1 );
}
return count;
}
}
[code]
Runtime: 14 ms, faster than 85.19% of Java online submissions for Subarray Sum Equals K.Memory Usage: 36.8 MB, less than 98.65% of Java online submissions for Subarray Sum Equals K.