首页 > 其他 > 详细

Minimum Size Subarray Sum -- leetcode

时间:2015-08-08 12:09:04      阅读:292      评论: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.



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

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

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

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!