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

Minimum Size Subarray Sum —— LeetCode

时间:2015-05-25 18:12:05      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

题目大意:给定一个非负数组,和一个指定值,找出最小子数组长度使得这个子数组的和大于指定的值。

解题思路:采用滚动计算的思路,类似rolling hash的思想,首先累加数组元素,当大于指定元素时——>执行(从这个子数组的第一个数开始,循环减去这些数),遍历一遍,得到最小子数组长度。

    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null||nums.length == 0) {
            return 0;
        }
        int min = 0,pos=0,len=Integer.MAX_VALUE;
        for (int i =0; i<nums.length; i++ ) {
            min+=nums[i];
            while(min>=s){
                if (len>i-pos+1) {
                    len=i-pos+1;
                }
                min-=nums[pos];
                pos++;
            }
        }
        return len==Integer.MAX_VALUE?0:len;
    }

 

Minimum Size Subarray Sum —— LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4528241.html

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