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

Minimum Size Subarray Sum

时间:2015-05-18 10:29:36      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

  双指针

我的代码:

技术分享
public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if(nums==null || nums.length==0)    return 0;
        int minLen = Integer.MAX_VALUE;
        int len = nums.length;
        int tmpSum = 0;
        
        for(int i=0,j=0; j<len; j++)
        {
            tmpSum += nums[j];
            if(tmpSum >= s)
            {
                while(i <= j)
                {
                    tmpSum -= nums[i];
                    if(tmpSum < s) 
                    {
                        tmpSum += nums[i];
                        break;    
                    }
                    else i++;
                }
                minLen = Math.min(minLen, j-i+1);
            }
        }
        
        return minLen==Integer.MAX_VALUE ? 0 : minLen;
    }
}
View Code

学习之处:

  • 双指针的用处在于,后面的指针用于确定下界,前面的指针用于确定上界,然后前面的指针一直再向后指针靠近,尽量压缩之间的距离,也就是要求得的距离
  • 明明规划,i 变成start j变成end 更好一点
  • 改掉自己的坏习惯,稳住心态,不焦虑

Minimum Size Subarray Sum

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4511234.html

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