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

Minimum Size Subarray Sum -- leetcode

时间:2015-08-08 12:11:52      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:leetcode   双指针   滑动窗口   

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;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

Minimum Size Subarray Sum -- leetcode

标签:leetcode   双指针   滑动窗口   

原文地址:http://blog.csdn.net/elton_xiao/article/details/47355857

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