[LeetCode] 930. Binary Subarrays With Sum

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.

A subarray is a contiguous part of the array.

Example 1:
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
Explanation: The 4 subarrays are bolded and underlined below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

Example 2:
Input: nums = [0,0,0,0,0], goal = 0
Output: 15

Constraints:
1 <= nums.length <= 3 * 104
nums[i] is either 0 or 1.
0 <= goal <= nums.length

和相同的二元子数组。

给你一个二元数组 nums ,和一个整数 goal ,请你统计并返回有多少个和为 goal 的 非空 子数组。

子数组 是数组的一段连续部分。

思路

这道题我提供两种做法,一是前缀和,二是滑动窗口。最优解是前缀和。

思路一 - 前缀和

创建一个变量 sum,在遍历 input 数组的同时把每个数字累加到 sum 上,并把每个 sum 和当前的 index 存到一个 map 中。如果在 map 中存在一个 key = sum - goal,说明存在一个子数组和为 goal,我们可以把 key 背后的 value 累加到结果里。

复杂度

时间O(n)
空间O(n)

代码

Java实现一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int sum = 0;
int res = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
res += map.getOrDefault(sum - goal, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return res;
}
}

Java实现二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
int n = nums.length;
int[] map = new int[n + 1];
map[0] = 1;
int sum = 0;
int res = 0;
for (int num : nums) {
sum += num;
if (sum >= goal) {
res += map[sum - goal];
}
map[sum]++;
}
return res;
}
}

思路二 - 滑动窗口

这道题可以用类似 992 题那样的滑动窗口的思路做,来找到子数组的和恰巧等于 goal 的子数组个数。

复杂度

时间O(n^2) - 接近于O(n^2)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int numSubarraysWithSum(int[] nums, int goal) {
return helper(nums, goal) - helper(nums, goal - 1);
}

private int helper(int[] nums, int limit) {
int res = 0;
int sum = 0;
int len = nums.length;
int start = 0;
int end = 0;
while (end < len) {
sum += nums[end];
end++;
while (start < end && sum > limit) {
sum -= nums[start];
start++;
}
res += end - start + 1;
}
return res;
}
}

[LeetCode] 930. Binary Subarrays With Sum
https://shurui91.github.io/posts/4050545082.html
Author
Aaron Liu
Posted on
May 5, 2021
Licensed under