Minimum Size Subarray Sum

来源:互联网 发布:数据集成日语怎么说 编辑:程序博客网 时间:2024/05/16 09:25

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.


双指针,用cmp保存数列的值,每次判断(前一保存数组与当前值的和) 与 当index前值的大小,如果小于当前index的值,说明前段数组小于零舍弃,从当前index计数。如果cmp大于s,则从left指针开始舍弃,直到cmp小于s,保存数组的长度,具体的代码如下

public class Solution {    public int minSubArrayLen(int s, int[] nums) {        if(nums.length<=0||s<=0) return 0;        int cmp = nums[0], res = 1,minRes = Integer.MAX_VALUE;        int left = 0;        if(cmp>=s) return res;        for(int i=1;i<nums.length;i++){        if(nums[i]>=cmp +nums[i]){        left = i;        cmp = nums[i];        res = 1;        }else{        cmp = cmp+nums[i];        res++;        }        if(cmp>=s){        while(cmp>=s){        cmp -= nums[left];        left++;        res--;        }        minRes = Math.min(res+1, minRes);        }        }        return minRes==Integer.MAX_VALUE?0:minRes;    }}







0 0