LC.P560[和为K的子数组]

方法一:前缀和

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int subarraySum(int[] nums, int k) {
int n = nums.length, ans = 0;
int[] sum = new int[n + 1];
for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + nums[i - 1];
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
if (sum[j + 1] - sum[i] == k) ++ans;
}
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$

方法二:前缀和+哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int subarraySum(int[] nums, int k) {
int pre = 0, ans = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int num : nums) {
pre += num;
if (map.containsKey(pre - k)) {
ans += map.get(pre - k);
}
map.merge(pre, 1, Integer::sum);
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$