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.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Hide Similar Problems
 (H) Minimum Window Substring

解题思路:题目大概的意思是寻找最短的数组和大于等于sum, 用遍历的思想。第一个到滴n个, 答案(如4,3)一定是按顺序搜索到的。

                   两个指针sum和end标定。start从0開始
                    (1)我们从下标0開始搜索大于sum的,
                  (2)假设大于sum,则start往后一格。,end记住位置
                   (3)假设start-往后走。sum减小之前的start上的数,此时sum还大于s返回2,否则返回(1)
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) 
		{
			if(nums.size()==0)
				return 0;
			 int start=0;
			 int end;
			 int numMin;
			 int AnswernumMin=INT_MAX;
			 int sum=0;
			for (int i=0;i<nums.size();i++)
			{
				sum+=nums[i];
				while(sum>=s)
				{
					end=i;
					numMin=end-start+1;//length  mean has 0 means 1,start=end;
					if (numMin<AnswernumMin)
					{
						AnswernumMin=numMin;
					}
					sum=sum-nums[start];
					start=start+1; //start forward one!
				}
			}
			if (AnswernumMin==INT_MAX)
			{
				return 0;
			}
			return AnswernumMin;
		}
};