leetcode - minimum size subarray sum
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.
========================================================
刚看到这个题目,我想到的就是移窗户。 先找到第一个>=7 的contiguous的 subarray, 然后记录这个为当前窗户
然后以这个窗户大小为标准,从第二个elem开始找到下一个>= 7 的subarray,一旦size 大于当前的窗户, 我们就break回到外loop。 如果说在当前窗户之内找到一个小于当前大小的subarray, 那我们就break并且跟新当前的subarray
这样的话runtime 应该是比o(n^2)要小一点, 但是效率还是不是很高
1 public int minSubArrayLen(int s, int[] nums) { 2 //find first window; 3 int windowSize = 0; 4 int sum = 0; 5 for (int i = 0; i < nums.length; i++) { 6 sum = sum + nums[i]; 7 if (sum >= s) { 8 windowSize = i + 1; 9 break; 10 } 11 } 12 sum = 0; 13 int start = 1; 14 while (start < nums.length) { 15 int end = start; 16 while (end - start + 1 < windowSize && end < nums.length) { 17 sum = sum + nums[end]; 18 if (sum >= s) { 19 windowSize = end - start + 1; 20 break; 21 } 22 end++; 23 } 24 sum = 0; 25 start++; 26 } 27 return windowSize; 28 }