暴力
class Solution {
//前缀和
public int minSubArrayLen(int s, int[] nums) {
int n = nums.length;
int res = n;
//[i,j)
int[] preSum = new int[n+1];
for(int i=1;i<=n;i++){
preSum[i] = preSum[i-1]+nums[i-1];
}
for(int i=0;i<n;i++){
for(int j=i+1;j<=n;j++){
int target = preSum[j] - preSum[i];
if(target >= s) res = Math.min(res,j-i);
}
}
return (res == n && preSum[n] < s)? 0 : res;
}
}
双指针(滑动窗口)
1、想清楚指针移动就好,初始i,j都指向0号元素,之后j不断后移,总和不断增加,直到大于等于s,记录长度j-i
2、之后l后移,总和减去nums[l]的值再判断是否还大于s,如果还大于重复第2步,否则执行第1步
class Solution {
//双指针(滑动窗口)
public int minSubArrayLen(int s, int[] nums) {
int n = nums.length;
int l= 0, r = 0,sum = 0;
int minLen = n;
while(l <= r && r <= n){
if(sum >= s){
minLen = Math.min(minLen,r-l);
sum -= nums[l];
l++;
}else{
if(r == n) break;
sum += nums[r];
r++;
}
}
return l == 0 ? 0 : minLen;
}
}