Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input:[2,3,1,2,4,3],
s = 7
Output: 2 Explanation: the subarray[4,3]
has the minimal length under the problem constraint.
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int i=0,j=0,sum=0; // 通过滑动窗口的方式
int res=INT_MAX;
for(;i<nums.size();++i){
sum+=nums[i];
while(sum>=s){
res=min(res,i-j+1);
sum-=nums[j++];
}
}
return res==INT_MAX?0:res;
}
};