forked from qiyuangong/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path560_Subarray_Sum_Equals_K.java
More file actions
28 lines (28 loc) · 888 Bytes
/
560_Subarray_Sum_Equals_K.java
File metadata and controls
28 lines (28 loc) · 888 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
public class Solution {
/*public int subarraySum(int[] nums, int k) {
int count = 0;
for (int start = 0; start < nums.length; start++) {
int sum = 0;
for (int end = start; end < nums.length; end++) {
sum += nums[end];
if (sum == k)
count++;
}
}
return count;
}*/
public int subarraySum(int[] nums, int k) {
int count = 0, sum = 0;
HashMap < Integer, Integer > map = new HashMap < > ();
map.put(0, 1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
// check if sum - k in hash
if (map.containsKey(sum - k))
count += map.get(sum - k);
// push sum into hash
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}