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.
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.
找到最小连续子数组,使得和大于等于给定值。
因为所有数都是正数,所以子数组的和满足单调性,两个点贪心扫一遍就可以了
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int res = 0, l = 0, r = 0;
int ans = INT_MAX;
while(r <= nums.size())
{
if(res >= s)
{
ans = min(ans, r - l);
res -= nums[l++];
}
else
{
if(r == nums.size()) break;
res += nums[r++];
}
}
return ans == INT_MAX ? 0 : ans;
}
};