您的位置:首页 > 其它

leetcode209-Minimum Size Subarray Sum(最小长度子数组和)

2016-01-25 23:15 435 查看
问题描述:

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)时间,O(1)空间。

class Solution {
public://动态滑窗解决。O(n)时间,O(1)空间。
int minSubArrayLen(int s, vector<int>& nums) {
int n=nums.size();
int cur_sum = 0;//当前的和
int min_size = INT_MAX;//子数组最小长度
int begin = 0, end = 0;//子数组起始位置
while(begin < n)
{
if(cur_sum<s && end<n)
{//(1)如果当前窗口的数相加没有达到s,则将窗口右移
cur_sum += nums[end++];
}
else if(cur_sum >= s)
{//(2)如果当前窗口的数相加等于或大于s,则收缩窗口
min_size = min(min_size, end-begin);//实为(end-1)-begin+1,之前end已经多加1。
cur_sum -= nums[begin++];
}
else
{//(3)cur_sum < s而且end>=n,则退出循环
break;
}
}
return (min_size==INT_MAX)?0:min_size;
}
};


方法二:在一的基础上简化下逻辑。其他不变。

class Solution {
public://动态滑窗解决。O(n)时间,O(1)空间。
int minSubArrayLen(int s, vector<int>& nums) {
int n=nums.size();
if(n == 0) return 0;
int min_size=INT_MAX;
int cur_sum=0;
int begin=0;
for(int end=0;end<n;end++)
{//依次遍历
//1.更新当前窗口和
cur_sum += nums[end];
while(cur_sum >= s)
{//2.如果当前和大于或等于s
//(1)更新最小长度
min_size = min(min_size, end-begin+1);
//(2)当前和减去窗口最前的数,并且窗口前指针后移
cur_sum -= nums[begin++];
}
}
return (min_size==INT_MAX)?0:min_size;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode