2015年10月24日星期六

Leetcode 209 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.
Solution 1: slide window.
 public class Solution {  
   public int minSubArrayLen(int s, int[] nums) {  
     int i=0, sum=0, n=nums.length;  
     int res=Integer.MAX_VALUE;  
     for (int j=0; j<n; j++) {  
       sum+=nums[j];  
       while (sum>=s) {  
         res=Math.min(res,j-i+1);  
         sum-=nums[i++];  
       }  
     }  
     if (res==Integer.MAX_VALUE) return 0;  
     return res;  
   }  
 }  

没有评论:

发表评论