标签: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