209. 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.

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

 解题思路:由于所有元素都为正数,所以求和肯定是不断增大的,用双指针法每次滑动窗口,当当前值大于s时,缩小窗口范围,每次大于s的时候都更新窗口大小。

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        if(nums.empty()||s==0)return 0;
        int i=0,j=0,sum=0,ans=INT_MAX;
        while(i<nums.size()){
            sum+=nums[i++];
            while(sum>=s){
                ans=min(ans,i-j);
                sum-=nums[j++];
            }
        }
        return ans==INT_MAX?0:ans;
    }
};

 

posted @ 2017-03-10 16:30  Tsunami_lj  阅读(97)  评论(0编辑  收藏  举报