[LeetCode] 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.

问题:给定一个正整数数组和一个正整数 s ,求连续子数组的和大于等于 s 的最小长度。

解题思路:采用滑动窗口算法(Slide Window Algorithm)。

设下标 l 和 r, 把左开右闭 [l, r) 想象成一个窗口。

  • 当窗口内的和 sum 小于 s 时, 则 r 向右滑动,增加窗口区间。
  • 当窗口内的和 sum 大于等于 s 时,表示已经满足原题目要求,是一个可行解,解 l 向右滑动,继续求解。
int minSubArrayLen(int s, vector<int>& nums) {
    
    int l = 0;
    int r = 0;
    
    int sum = 0;
    int res = intMax;
    
    while (r < nums.size()) {
        sum += nums[r];
        r++;
        while (sum >= s) {            
            res = min(res, r-l);
            sum = sum - nums[l];
            l++;
        }
    }
    
    return (res == intMax) ? 0 : res;
}

 

额外记录:

Slide Window Algorithm 可能不是一个正式的称谓,因为在 wikipedia 没有找到介绍。

遇到求最小 / 最大连续子数组,好像都可以考虑使用 Slide Window Algorithm 。

 

参考资料:

LeetCode Minimum Size Subarray Sum, jyuan

 

posted @ 2015-12-19 15:50  TonyYPZhang  阅读(791)  评论(0编辑  收藏  举报