Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous 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.
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
本题目因为数组元素都是正数,没有有正有负的难,代码如下:
1 public class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 int len = nums.length; 4 int left = -1; 5 int sum = 0; 6 int key = 0; 7 for(int i=0;i<nums.length;i++){ 8 key+=nums[i]; 9 sum+=nums[i]; 10 if(sum>=s){ 11 while(sum-nums[left+1]>=s){ 12 sum-=nums[++left]; 13 } 14 len = Math.min(len,i-left); 15 } 16 } 17 if(key<s) return 0; 18 return len; 19 } 20 }
209. Minimum Size Subarray Sum
原文:http://www.cnblogs.com/codeskiller/p/6489865.html