ITPub博客

首页 > > > [LeetCode] Minimum Size Subarray Sum

[LeetCode] Minimum Size Subarray Sum

作者:Ruiyuan Li 时间:2015-05-12 00:00:00 0 删除 编辑

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& nums) {
        int size = nums.size();
        int len = 1;
        while(len<=size){
            int sum = 0;
            for(int j=0; j=s){
                return len;
            }
            int start = 0;
            int end = start + len - 1;
            while(end + 1=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& nums) {
        int size = nums.size();
        if(size==0){
            return 0;
        }
        int minLen = size + 1;
        int sum = 0;
        int start=0, end=0;
        while(end=s){
                minLen = min(minLen, end - start);
                if(minLen == 1){
                    return minLen;
                }
                sum -= nums[start];
                start++;
            }
        }
        
        return minLen==size + 1?0:minLen;
    }
};


<!-- -->

原文作者:;如有侵权,请联系管理员删除。

上一篇: c#发送邮件
下一篇: [LeetCode] Candy
请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825