zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    Windows 7 远程协助
    Windows 7 帮助和支持资源—第三方网站
    Windows 7 帮助和支持资源—第三方软件
    数据结构-队列
    数据结构-栈
    pycharm每日技巧-2
    数据结构-链表
    时间处理-1
    二维数组的排序
    《疯狂的简洁》书摘
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5059248.html
Copyright © 2011-2022 走看看