您的位置:首页 > 其它

Minimum Size Subarray Sum

2016-05-29 21:30 246 查看
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.

这道题给定了我们一个数字,让我们求子数组之和大于等于给定值的最小长度,跟之前那道 Maximum Subarray 最大子数组有些类似,并且题目中要求我们实现O(n)和O(nlgn)两种解法,那么我们先来看O(n)的解法,我们需要定义两个指针left和right,分别记录子数组的左右的边界位置,然后我们让right向右移,直到子数组和大于等于给定值或者right达到数组末尾,此时我们更新最短距离,并且将left像右移一位,然后再sum中减去移去的值,然后重复上面的步骤,直到right到达末尾,且left到达临界位置,即要么到达边界,要么再往右移动,和就会小于给定值。代码如下:

class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if(nums.empty())
return 0;
int left = 0;
int right = 0;
int sum = 0;
int len = nums.size();
int res = INT_MAX;
while(right < len){
while(sum <s && right<len){
sum += nums[right++];

}
if(sum>=s){
res = min (res,right-left);
sum -= nums[left++];
}
}
if(res == INT_MAX)
return 0;
else
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode