class Solution {
public int subarraySum(int[] nums, int k) {
HashMap<Long,Integer> hm=new HashMap<>();
long sum=0;
int cnt=0;
hm.put(sum,1);
for(int i=0;i<nums.length;i++){
sum+=nums[i];
if(hm.containsKey(sum-k)){
cnt+=hm.get(sum-k);
}
if(hm.containsKey(sum)){
hm.put(sum,hm.get(sum)+1);
}
else{
hm.put(sum,1);
}
}
return cnt;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter