Minimum Size Subarray Sum -- leetcode

来源:互联网 发布:订单生成器软件下载 编辑:程序博客网 时间:2024/06/07 20:07

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.



基本思路:滑动窗口,双指针

一个指针在前,进行不断的累加;

当累加和超过指定阀值后,一个指针在后,不断累减,直到累加和小于给定阀值。

形象的看起来,有如一个保持阀值宽度的窗口,从左向右滑动。

O(n)


class Solution {public:    int minSubArrayLen(int s, vector<int>& nums) {        int i = 0, j = 0, ans = INT_MAX, sum = 0;        for (int i=0; i<nums.size(); i++) {            sum += nums[i];            while (sum >= s) {                ans = min(ans, i-j+1);                sum -= nums[j++];            }        }        return ans == INT_MAX ? 0 : ans;    }};


0 0
原创粉丝点击