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.

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 numsSize = nums.size();
        int i=-1,j=0;
        int sum=0;
        int minLen = numsSize+1;
        while(i<j){
            if(sum<s){
                if(j>=numsSize){
                    break;
                }
                sum+=nums[j++];
            }else if(sum>=s){
                minLen = min(minLen,j-i-1);
                sum-=nums[++i];
            }
        }
        return minLen==numsSize+1 ? 0:minLen;
    }
};

 2.o(nlgn)

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int numsSize = nums.size();
        int low = 0,high=numsSize+1;
        while(low<high){
            int mid = low+(high-low)/2;
            int sum = 0;
            for(int i=0;i<numsSize;i++){
                sum+=nums[i];
                if(i>=mid){
                    sum-=nums[i-mid];
                }
                if(sum>=s){
                    break;
                }
            }
            if(sum>=s){
                high = mid;
            }else{
                low = mid+1;
            }
        }
        return low==numsSize+1 ? 0:low;
    }
};

 

posted @ 2015-11-30 10:47  zengzy  阅读(200)  评论(0编辑  收藏  举报
levels of contents