Minimum Size Subarray Sum

来源:互联网 发布:jdk 7u79 windows x86 编辑:程序博客网 时间:2024/06/05 23:38

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

方法1:O(n) 算法

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

方法2: O(nlog(n))算法。

class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {        vector<int> accumulate(nums.size()+1,0);        int minLen = INT_MAX;        int sum = 0;        for(int i=1;i<accumulate.size();++i)            accumulate[i]=accumulate[i-1]+nums[i-1];        for(int i=0;i<accumulate.size()-1;++i){            int target = s + accumulate[i];            int pos = upperbound(accumulate,target,i+1,accumulate.size()-1);            if(pos==-1)                continue;            minLen = min(minLen,pos-i);        }        return minLen==INT_MAX?0:minLen;    }private:    int upperbound(vector<int>& accumulate,int target,int left,int right){        if(accumulate[right]<target)            return -1;        while(left<right){            int middle = (left+right)/2;            if(accumulate[middle]<target)                left=middle+1;            else                right=middle;        }        return left;    }};
0 0