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的连续序列的长度;
解题思路:维护l、r分别保存序列的起始结束下标,依次扫描所给数组,当sum < s 时,r+=1,当sum > s时,l+=1,直至扫描结束。
int minSubArrayLen(int s, vector<int>& nums) {
if(nums.empty()) return 0;
int sum = 0;
int ans = INT_MAX, count = 0;
int l = 0, r = 0;
while(r < nums.size() || sum >= s ){
//当序列和小于s时,r++
if(sum < s){
sum += nums[r++];
count++;
}
//当序列长度大于当前最短序列的长度或序列和大于s时,l++
if(sum >= s || count > ans){
ans = min(ans, count);
//如果长度为1,则直接返回
if(ans == 1)return ans;
sum -= nums[l++];
count--;
}
}
if(ans == INT_MAX) return 0;
return ans;
}