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

LeetCode OJ:Minimum Size Subarray Sum(最小子数组的和)

时间:2015-10-20 17:45:08      阅读:163      评论: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.

给一个数组以及一个数字,求满足大于该数字的最小的连续的数组元素个数的最小值。

代码写的比较乱。具体的思想就是用两个指针,一个先向前走, 当相加之和大于s的时候,将另一个指针也向前走,并减去相应的数字,当小于的时候将元素的个数存入数组,代码如下:

 1 class Solution {
 2 public:
 3     int minSubArrayLen(int s, vector<int>& nums) {
 4         int sz = nums.size();
 5         vector<int> ret;
 6         if(sz == 0) return 0;
 7         int i = 0;
 8         int j = 0;
 9         int tmpSum = 0;
10         while(j < sz){
11             for( ; i < sz; ++i){
12                 tmpSum += nums[i];
13                 if(tmpSum >= s)
14                     break;
15             }
16             if(tmpSum < s) break; //i已经达到数组的末尾了
17             for( ; j <= i; ++j){
18                 tmpSum -= nums[j];
19                 if(tmpSum < s)
20                     break;
21             }
22             ret.push_back(i - j + 1);
23             i++, j++;
24         }
25         sz = ret.size();
26         if(sz == 0) return 0;
27         int min = ret[0];
28         for(int i = 1; i < sz; ++i){
29             if(min > ret[i])
30                 min = ret[i];
31         }
32         return min;
33     }
34 };

 

LeetCode OJ:Minimum Size Subarray Sum(最小子数组的和)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4895463.html

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