Minimum Size Subarray Sum 滑动窗口移位

来源:互联网 发布:电脑视频壁纸软件 编辑:程序博客网 时间:2024/06/16 21:09

Minimum Size Subarray Sum

 

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.

click to show more practice.

class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {                if(nums.size()==0)            return 0;        int left,right,sum,minLen=9999999;                sum=0;        for(left=0,right=0;right<nums.size();)        {            while(sum<s&&right<nums.size())            {                sum+=nums[right];                right++;            }            if(sum>=s&&right-left<minLen)            {                minLen=right-left;            }            while(sum>=s)            {                sum-=nums[left];                left++;                if(sum>=s&&right-left<minLen)                {                    minLen=right-left;                }            }        }        if(minLen==9999999)              return 0;        return minLen;    }};

0 0
原创粉丝点击