(leetcode)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.

使用两个指针,start,end,当sum(start,end) < s时,就end++;

否则,将start前移知道找到第一个sum<s的start,并记录最小长度end-start,每次更新最小

 1 class Solution {
 2 public:
 3 // For example, given the array [2,3,1,2,4,3] and s = 7,
 4 // the subarray [4,3] has the minimal length under the problem constraint.
 5     int retmin(int a,int b)
 6     {
 7         return a<b?a:b;
 8     }
 9     int minSubArrayLen(int s, vector<int>& nums) {
10         int start = 0;
11         int end = 0;
12         int sum = 0;
13         int min = INT_MAX;
14 
15         while(start<nums.size() && end<nums.size())
16         {
17             while(sum < s && end < nums.size()) sum+=nums[end++];
18             while(sum >= s && start <= end) 
19             {
20                 min = retmin(min,end-start);
21                 sum -= nums[start++];
22             }
23             
24         }
25         return min==INT_MAX ?0:min;
26     }
27 }; 

 

posted @ 2015-08-24 11:14  sunalive  Views(144)  Comments(0)    收藏  举报