码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Minimum Size Subarray Sum 解题思路

时间:2015-12-19 16:32:00      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode] Minimum Size Subarray Sum 解题思路

标签:

原文地址:http://www.cnblogs.com/TonyYPZhang/p/5059248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!