Minimum Size Subarray Sum:
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.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Solution:
#include <iostream>
#include <vector>
using namespace std;
// 时间复杂度:o(n)
// 空间复杂度:o(1)
// 滑动窗口的思路
class Solution{
public:
int minSubArrayLen(int s, vector<int>& nums) {
int l = 0, r = -1; // nums[l...r]为滑动窗口
int sum = 0;
int res = nums.size() + 1;
while ( l < nums.size() ){
if ( r + 1 < nums.size() && sum < s ){
r ++;
sum += nums[r];
} else {
sum -= nums[l++];
}
if ( sum >= s ) {
res = min( res, r - l + 1);
}
}
if ( res == nums.size() + 1 )
return 0;
return res;
}
};
int main() {
return 0;
}