Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3]
and s = 7
,
the subarray [4,3]
has the minimal length under the problem constraint.
使用两个指针,start,end,当sum(start,end) < s时,就end++;
否则,将start前移知道找到第一个sum<s的start,并记录最小长度end-start,每次更新最小
class Solution {
public:
// For example, given the array [2,3,1,2,4,3] and s = 7,
// the subarray [4,3] has the minimal length under the problem constraint.
int retmin(int a,int b)
{
return a<b?a:b;
}
int minSubArrayLen(int s, vector<int>& nums) {
int start = ;
int end = ;
int sum = ;
int min = INT_MAX; while(start<nums.size() && end<nums.size())
{
while(sum < s && end < nums.size()) sum+=nums[end++];
while(sum >= s && start <= end)
{
min = retmin(min,end-start);
sum -= nums[start++];
} }
return min==INT_MAX ?:min;
}
};