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.
基本思路:滑动窗口,双指针
一个指针在前,进行不断的累加;
当累加和超过指定阀值后,一个指针在后,不断累减,直到累加和小于给定阀值。
形象的看起来,有如一个保持阀值宽度的窗口,从左向右滑动。
O(n)
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int i = 0, j = 0, ans = INT_MAX, sum = 0;
for (int i=0; i<nums.size(); i++) {
sum += nums[i];
while (sum >= s) {
ans = min(ans, i-j+1);
sum -= nums[j++];
}
}
return ans == INT_MAX ? 0 : ans;
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
Minimum Size Subarray Sum -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/47355857