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

文章标题

时间:2015-07-15 09:34:47      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:leetcode

链接:https://leetcode.com/problems/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.

Hide Tags Array Two Pointers Binary Search
Hide Similar Problems (H) Minimum Window Substring

给出数组和一个数字s,求数组中的一个最小区间,区间内的和大于等于s。总体思想和Minimum Window Substring 这一题相似。采用双指针的思想,计算p1和p2之间的和如果和小于s则p2++,如果大于等于s就更新最小值同时p1++。

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {

        int p1=0,p2=0,sum=0;
        int min=INT_MAX;
        while(p2<nums.size()||sum>s)
        {
          if(p1==p2)
          {
             sum=nums[p2++];
             if(sum>=s)
                 return 1;
          }
          else if(sum<s)
              sum+=nums[p2++];

          else if(sum>=s)
          {
           if(p2-p1<min)
             min=p2-p1;
           sum-=nums[p1++];
          }

        }
        if(sum>=s&&p2-p1<min)
          min=p2-p1;
        if(min==INT_MAX)
            return 0;
        return  min;
    }
};

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

文章标题

标签:leetcode

原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46885135

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