码迷,mamicode.com
首页 > 编程语言 > 详细

大于或等于给定值 长度最小的子数组 minimum size subarray sum [209]

时间:2016-06-01 21:00:54      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

leetcode 209

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.

===========

给定一个整数数组int a[] = {2,3,1,2,4,3},给定一个整数数字s;

求在a中子数组累加和 大于等于s中,长度最小的子数组长度;否则返回0;

一种时间复杂度o(n)的算法。

class A{
  public:
   int minSubArrayLen(int s, vector<int>& nums) {
        int start = 0;
        int minlen = INT_MAX;
        int tsum = 0;
        for(int i = 0;i<(int)nums.size();i++){
            tsum +=nums[i];
            while(tsum >= s){
                minlen = min(minlen,i-start+1);
                tsum = tsum - nums[start++];///关键是这一步,当tsum>=3是,start下标一直前进,而i下标是不变的
            }
        }
        return minlen==INT_MAX? 0: minlen;
    }
};

 

大于或等于给定值 长度最小的子数组 minimum size subarray sum [209]

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5550834.html

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