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:s = 7, nums = [2,3,1,2,4,3]
Output: 2 Explanation: the subarray[4,3]
has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
/* 找到一个满足条件的最小长度的连续子列和 滑动窗口
* sum 统计left-right之间的和 sum>s 是sum -= nums[left++]
* */
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if(nums.empty()) return 0;
int left=0, right=0, minlen=INT_MAX, sum=0, len=nums.size();// 和满足时移动左窗口
while(right<len){// 不停移动right 和移动left轮着来
while(right<len && sum<s){
sum += nums[right++];
}
while(sum >= s){
minlen = min(minlen, right-left);// 这里的right其实多进行了加1 故要再进行减一
sum -= nums[left++];
}
}
return minlen==INT_MAX ? 0 : minlen;
}
};