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.
代码如下:(超时)
1 public class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 // int min=Integer.MAX_VALUE; 4 int min=nums.length+1; 5 6 if(nums.length==0) 7 return 0; 8 9 10 for(int i=0;i<nums.length-1;i++) 11 { 12 int sum=nums[i],count=1; 13 if(sum>=s) 14 return count; 15 for(int j=i+1;j<nums.length;j++) 16 { 17 sum+=nums[j]; 18 count++; 19 if(count>=min) 20 break; 21 22 if(sum>=s) 23 { 24 if(count<min) 25 min=count; 26 break; 27 } 28 } 29 30 } 31 32 if(min==nums.length+1) 33 return 0; 34 35 return min; 36 } 37 }
浙公网安备 33010602011771号