[LeetCode] Minimum Size Subarray Sum

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.

解题思路:

注意这里的subarray是只顺序不可变,故不可以用先排序后选择的方法。

1、暴力滑动窗口法。依次验证窗口大小为1,2,3...的窗口,看看是否有和大于给定值的子数组。时间复杂度为O(n^2),空间复杂度为1

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int size = nums.size();
        int len = 1;
        while(len<=size){
            int sum = 0;
            for(int j=0; j<len; j++){
                sum += nums[j];
            }
            if(sum>=s){
                return len;
            }
            int start = 0;
            int end = start + len - 1;
            while(end + 1<size){
                sum -= nums[start];
                sum += nums[end+1];
                if(sum>=s){
                    return len;
                }else{
                    start++;
                    end++;
                }
            }
            len++;
        }
        return 0;
    }
};

2、伸缩窗口法。用两个指针start,end,若start和end-1之间的和小于s,end增加,若大于等于s,start增加,然后记录大于等于s时最小的长度。这种办法时间复杂度为O(n),空间复杂度为1。

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


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注