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).
题目的意思是给一个包含n个全部都是正数的数组和一个正数s,找到最小的子数组,这个子数组呢,一些元素的和呢要大于等于s.比如:【1,2,1,3,4,6,5】和为9,那么有两个子数组包含和为9,【2,1,3,4】和【4,6,5】一个长度为4一个长度为3所以返回3。刚开始一直没有理解题意。理解题意,那么O(n)的解题方法很简单,滑动窗口就可以了,然后在这个过程中记录值长度最小的值就可以了。
还是以【1,2,1,3,4,6,5】和9为例。分别用left和right记录滑动窗口的两端。刚开始left=0,right=0,窗口大小为0,所以增大right,当然right的值要小于数组的长度。这个时候sum+=nums[right].如果sum>=s而且还没有到达边界。这个时候记录下该窗口大小的值。然后将窗口变小,直到和小于s为止。然后继续向后滑动,直到结束为止。代码如下:
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if(nums.empty()){
return 0;
}
int n=nums.size();
int left=0,right=0,minLen=n+1,sum=0;
while(right<n){ //窗口不能超出右边界
while(sum<s && right<n ){ //向右扩大窗口,直到大于s为止。
sum+=nums[right++];
}
while(sum>=s){
minLen=min(minLen,right-left); //比较当前窗口的大小。
sum-=nums[left++]; //缩小窗口
}
}
return minLen==n+1?0:minLen;
}
};
另一种