码迷,mamicode.com
首页 > 其他好文 > 详细

Minimum Size Subarray Sum

时间:2015-05-16 09:13:30      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:leetcode   two pointer   说指针   

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;
    }
}







Minimum Size Subarray Sum

标签:leetcode   two pointer   说指针   

原文地址:http://blog.csdn.net/guorudi/article/details/45750427

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!