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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
题目意思是求大于给定数的子串和的最小长度。
可以用双指针做,类似滑动窗口。
定义一个left指针一个right指针,开始都指向头,然后如果sum<s则right不断向右,sum不断增大,然后left不断向右,sum不断减小,直到小于s。
class Solution {
public:
//定义两个指针,一个左指针,一个右指针,开始都指向头,然后右指针向后直到满足条件,记录长度,则left向后一位,重复
int minSubArrayLen(int s, vector<int>& nums) {
if (!nums.size()) return 0;
int sum = 0;
int left = 0, right = 0,size=nums.size();
int mincount = size;
bool flag = false;
while (right<size)
{
while (right<size&&sum<s)
{
sum += nums[right++];
}
while(sum>=s)//满足条件
{
mincount = min(right - left,mincount);
flag = true;
sum -= nums[left++];
}
}
if (flag) return mincount;
return 0;
}
};