力扣链接:力扣
思路
长度等于target的子数组有多个,想要确定最小的需要使用Math.min来更新最小数。初始化result = Integer.MAX_VALUE。
滑动窗口
- 所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。
- 在暴力解法中,是一个for循环滑动窗口的起始位置,一个for循环为滑动窗口的终止位置,用两个for循环 完成了一个不断搜索区间的过程。
- 滑动窗口只用一个for循环,那么这个循环的索引,一定是表示 滑动窗口的终止位置。
前缀和+二分查找
- 通过求取前缀和保存在新数组中,因为题目已知数组中为正整数,所以新数组中为单调不减的正整数。
- 在前缀和中,由后面的数减去前面的数算出子数组和,就可以通过遍历新数组查询target加上数组元素的和是否在新数组中。
Java
滑动窗口
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int result = Integer.MAX_VALUE;
int i = 0, sum = 0;
for(int j = 0; j < nums.length; j++) {
sum += nums[j];
while(sum >= target) {
result = Math.min(result, j - i + 1);
sum -= nums[i++];
}
}
return result = result == Integer.MAX_VALUE ? 0 : result;
}
}
前缀和+二分查找
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int ans = Integer.MAX_VALUE;
int[] sums = new int[n + 1];
// 为了方便计算,令 size = n + 1
// sums[0] = 0 意味着前 0 个元素的前缀和为 0
// sums[1] = A[0] 前 1 个元素的前缀和为 A[0]
// 以此类推
for (int i = 1; i <= n; i++) {
sums[i] = sums[i - 1] + nums[i - 1];
}
for (int i = 1; i <= n; i++) {
int target = s + sums[i - 1];
int bound = Arrays.binarySearch(sums, target);
if (bound < 0) {
bound = -bound - 1;
}
if (bound <= n) {
ans = Math.min(ans, bound - (i - 1));
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}