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.
双指针的思路,小于s,++r。大于s,–l。注意边界
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int l, r, Min, sum;
l = 0;
r = 1;
if(nums.empty()) return 0;
Min = nums.size() + 1;
sum = nums[l] + nums[r];
while(1){
if(nums[r] >= s || nums[l] >= s) return 1;
else if(sum >= s){
Min = Min > (r - l + 1) ? (r - l + 1) : Min;
if(l < nums.size()){
sum -= nums[l];
++l;
}
} else if(sum < s) {
if(r < nums.size() - 1)
++r;
else
break;
sum += nums[r];
}
}
return Min == nums.size() + 1 ? 0 : Min;
}
};