Given an array of n positive integers and a positive integer s, find the minimal length of a 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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
思路一:
1)设置两个指针l和r,先从左向右累加元素直至sum>=s;
2)累计减去前面的元素直至sum<s,并在重复减去前面元素的过程中保存最小长度res;
3)返回正确的结果。
该方法的时间复杂度为O(n)。
代码实现:
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int l, r, sum, res = nums.size()+1;
l = r = sum = 0;
while (r < nums.size()) {
sum += nums[r++];
while (sum >= s) {
res = min(res, r-l);
sum -= nums[l++];
}
}
return res<=nums.size()?res:0;
}
};