209.Minimum Size Subarray Sum

来源:互联网 发布:淘宝客公众号系统搭建 编辑:程序博客网 时间:2024/06/10 14:08

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.

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

Credits:

Special thanks to @Freezen for adding this problem and creating all test cases.

O(n)滑动窗口,先固定窗口的左侧,窗口右侧不断向后,当窗口内的数字之和大于s是,将窗口左侧往后移,更新窗口内数字之和,再次检查窗口内数字之和是否大于s,如果是则继续将窗口左侧后移,否则,固定窗口左侧而将窗口右侧后移。

class Solution {public:int minSubArrayLen(int s, vector<int>& nums) {    int firstPos = 0, sum = 0, minLength = INT_MAX;    for(int i = 0; i<nums.size(); i++)     {        sum += nums[i];        while(sum >= s)         {            minLength = min(minLength, i - firstPos + 1);            sum -= nums[firstPos++];        }    }    return minLength == INT_MAX? 0 : minLength;  }};


O(nlogn)二分查找,对窗口的长度进行二分查找

class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {        int len = nums.size();        int left = 0;        int right = len;        int ret = 0;        int mid = 0;        while(left <= right)        {            mid = left + (right - left)/2;            if(windowExist(mid,s,nums))            {                ret = mid;                right = mid-1;            }            else                left = mid + 1;        }                return ret;            }        //check if a window of size len exists    bool windowExist(int len,int s,vector<int>& nums)    {        int sum = 0;        for(int i = 0;i<nums.size();++i)        {                        if(i>=len)                sum-=nums[i-len];            sum+=nums[i];            if(sum >= s)                return true;                    }                return false;    }};


0 0
原创粉丝点击