Binary Subarrays With Sum LeetCode solution in Java

1
class Solution {
2
public int numSubarraysWithSum(int[] nums, int goal) {
3

4
int pre=0,cnt=0;
5
HashMap<Integer,Integer> m=new HashMap();
6
for(int i:nums){
7

8
pre+=i;
9
// if(pre-goal<0)continue;
10
if(pre-goal==0)cnt++;
11

12
if(m.containsKey(pre-goal)){
13
cnt+=m.get(pre-goal);
14

15

16
}
17
m.put(pre,m.getOrDefault(pre,0)+1);
18

19

20

21
}
22

23
return cnt;
24
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0