• 【LeetCode】209. 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.

    click to show more practice.

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    典型的双指针滑动窗口,前指针扩展,后指针收缩。

    记录下每一次sum of [begin, end] ≥ s时候的窗口大小即可。

    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) {
            if(nums.empty())
                return 0;
            int ret = INT_MAX;
            int n = nums.size();
            int begin = 0;
            int end = 0;
            int cursum = nums[0];   // guaranteed to exist
            while(end < n)
            {
                // expand
                while(end < n && cursum < s)
                {
                    end ++;
                    cursum += nums[end];
                }
                if(end == n)    // cursum of [begin, n) < s
                    break;
                // shrink (cursum >= s)
                while(begin <= end && cursum >= s)
                {
                    ret = min(ret, end-begin+1);
                    cursum -= nums[begin];
                    begin ++;
                }
                end ++;
                cursum += nums[end];
            }
            if(ret == INT_MAX)
                return 0;
            else
                return ret;
        }
    };

  • 相关阅读:
    HTML5之dir属性
    IPv4地址分类及子网划分
    二叉树的3种遍历
    js的点表示法和方括号表示法
    javascript-数组的常用方法
    第一编博文——漫长编程路
    使用qemu
    initial ram disk
    qemu常见选项解析
    cp和scp
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4609603.html
Copyright © 2020-2023  润新知