Given an array of integers and an integer k, find the total number of continuous subarrays whose sum equals to
k.
Example 1:
Input:nums = [1,1,1], k = 2 Output: 2
Note that empty array is not considered as a subarray.
public class CountSubarraySumEqualsK {
public static void main(String[] args) {
int arr[] = {3,9,-2,4,1,-7,2,6,-5,8,-3,-7,6,2,1};
//int arr[] = {1,1,2};
Map<Integer,Integer> map= new HashMap<>();
int sum = 0;
int count = 0;
int k = 5;
// int k =2;
for(int i = 0;i<arr.length;i++){
sum+=arr[i];
if(sum==k){
count++;
}
int diff = sum-k;
if(map.containsKey(diff)){
count = count + map.get(diff);
}
if(map.containsKey(sum)){
map.put(sum,map.get(sum)+1);
}else{
map.put(sum,1);
}
}
System.out.println(count);
}
}
No comments:
Post a Comment