-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarray_Sum_Equals_K.java
More file actions
42 lines (32 loc) · 933 Bytes
/
Copy pathSubarray_Sum_Equals_K.java
File metadata and controls
42 lines (32 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
A subarray is a contiguous non-empty sequence of elements within an array.
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
*/
import java.util.*;
class Subarray_Sum_Equals_K {
public int subarraySum(int[] nums, int k) {
int prefix = 0;
int count = 0;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0,1);
for(int i =0 ; i<nums.length ; i++){
prefix = prefix + nums[i];
int need = prefix - k ;
if(map.containsKey(need)){
count = count + map.get(need);
}
map.put(prefix , map.getOrDefault(prefix , 0)+1);
}
return count ;
}
}