209. Minimum Size Subarray Sum
1. Two pointer
runner只走一遍,每次往前走一格,如果walker可以往前缩就一直缩到依旧满足条件的最远的位置。
最后不要忘了检查有没有满足条件的,如果没有就返回0
1 public int minSubArrayLen(int s, int[] nums) { 2 if(nums.length == 0) { 3 return 0; 4 } 5 int walker = 0; 6 int runner = 0; 7 int curSum = 0; 8 int minLen = Integer.MAX_VALUE; 9 while(runner < nums.length) { 10 curSum += nums[runner]; 11 runner++; 12 while(curSum - nums[walker] >= s) { 13 curSum -= nums[walker]; 14 walker++; 15 } 16 if(curSum >= s) { 17 minLen = Math.min(minLen, runner - walker); 18 } 19 } 20 return minLen == Integer.MAX_VALUE? 0: minLen; 21 }
所以时间复杂度是O(n)
2. NlogN方法