-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
45 lines (34 loc) · 967 Bytes
/
Solution.java
File metadata and controls
45 lines (34 loc) · 967 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
43
44
45
package subarraysumequalsk;
import java.util.HashMap;
import java.util.Map;
class Solution {
public static int subarraySum(int[] nums, int k) {
Map<Integer, Integer> minuses = new HashMap<>();
int total = 0;
if (nums[0] == k) {
total++;
}
minuses.put(nums[0], 1);
int newSum;
int prevSum = nums[0];
for (int i=1; i<nums.length; i++) {
newSum = prevSum + nums[i];
Integer number = minuses.get(newSum - k);
if (number != null) {
total += number;
}
if (newSum == k) {
total++;
}
minuses.merge(newSum, 1, Integer::sum);
prevSum = newSum;
}
return total;
}
public static void main(String[] args) {
int k = 2;
int[] arr = new int[]{1,1,1};
int i = subarraySum(arr, k);
System.out.print(i);
}
}