-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
28 lines (25 loc) · 889 Bytes
/
Solution.java
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
package g0501_0600.s0560_subarray_sum_equals_k;
// #Medium #Top_100_Liked_Questions #Array #Hash_Table #Prefix_Sum #Data_Structure_II_Day_5_Array
// #Big_O_Time_O(n)_Space_O(n) #2022_08_03_Time_21_ms_(98.97%)_Space_46.8_MB_(88.27%)
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int subarraySum(int[] nums, int k) {
int tempSum = 0;
int ret = 0;
Map<Integer, Integer> sumCount = new HashMap<>();
sumCount.put(0, 1);
for (int i : nums) {
tempSum += i;
if (sumCount.containsKey(tempSum - k)) {
ret += sumCount.get(tempSum - k);
}
if (sumCount.get(tempSum) != null) {
sumCount.put(tempSum, sumCount.get(tempSum) + 1);
} else {
sumCount.put(tempSum, 1);
}
}
return ret;
}
}