209. Minimum Size Subarray Sum
Difficulty: Medium
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.
思路
找到数组中元素之和大于等于s的最小子数组。
依次遍历元素,将当前遍历的元素添入子数组,若子数组中元素之和不小于s,当前子数组的长度和之前的最短数组长度比较取较小值。此外,将子数组前面的元素移除,直到子数组元素之和小于s,再遍历下一元素。最后返回记录的最短数组长度。
代码
[C++]
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int sum = 0;
int minlen = 0;
int start = 0;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
while (sum >= s && start <= i) {
if (minlen == 0 || minlen > i - start + 1)
minlen = i - start + 1;
sum -= nums[start];
start++;
}
}
return minlen;
}
};