-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path560_subarray_sum_equals_k.java
More file actions
79 lines (67 loc) · 1.97 KB
/
560_subarray_sum_equals_k.java
File metadata and controls
79 lines (67 loc) · 1.97 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* Solution 01: Prefix-sum */
class Solution {
public int subarraySum(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] sums = new int[nums.length];
int count = 0;
for (int i = 0; i < nums.length; i++) {
sums[i] = (i == 0) ? nums[i] : sums[i - 1] + nums[i];
if (sums[i] == k) {
count ++;
}
}
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j ++) {
if (sums[j] - sums[i] == k) {
count ++;
}
}
}
return count;
}
}
/* Solution 02: Prefiix-sum without space */
class Solution {
public int subarraySum(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
int sum = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
sum = 0;
for (int j = i; j < nums.length; j ++) {
sum += nums[j];
if (sum == k) {
count ++;
}
}
}
return count;
}
}
/* Solution 03: Prefix-sum with hashmap */
class Solution {
public int subarraySum(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
Map<Integer, Integer> map = new HashMap<>();
int[] sums = new int[nums.length];
int count = 0;
for (int i = 0; i < nums.length; i++) {
sums[i] = (i == 0) ? nums[i] : sums[i - 1] + nums[i];
if (sums[i] == k) {
count ++;
}
if (map.containsKey(sums[i] - k)) {
count += map.get(sums[i] - k);
}
int sumCount = map.getOrDefault(sums[i], 0);
map.put(sums[i], sumCount + 1);
}
return count;
}
}