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.
分析:
题目给定一个正数数组,及正数s,需要寻找连续子数组之和大于等s的最短长度。这里可以采用滑动窗口的思想进行求解。设两个索引l、r,计算[l,r]区间内元素之和,若元素之和小于s,则r++增加连续子数组内的元素个数,反之l++,减少连续子数组内元素个数,进而使得连续子数组内元素之和减小。若连续子数组元素和大于等于s,则记录当前连续子数组长度与原记录值得最小值(该值初始化为nums.size()+1)
代码:
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int l = 0;
int r = -1;
int res = nums.size() + 1;
int sum = 0;
while(l < nums.size())
{
if (r+1 < nums.size() && sum < s)
{
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;
}
};