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 has the [4,3] minimal length under the problem constraint.
The problem is mainly to clarify the requirements of the topic first. First of all, if there is not one of the topics mentioned, return 0 instead. What's not to be considered?
This means that if we calculate the length of min length and the array itself, then we should return 0.
It's easier to think of it in terms of the pointer. A pointer is used to calculate sum, and another pointer immediately followed to determine the length.
The code is as follows. ~
public class Solution {public int Minsubarraylen (int. s, int[] nums) { //two pointer //one from Start;one Foll ows int start = 0; int end = 0; int sum = 0; int min = nums.length; while (Start<nums.length && end<nums.length) {while (sum<s && end<nums.length) { Sum=sum+nums[end]; end++; } while (Sum>=s && start<=end) { min = math.min (min, end-start); Sum =sum-nums[start]; start++; } } if (min==nums.length) { return 0; } return min; }}
[Leetcode] Minimum Size Subarray Sum