LeetCode 209. Minimum Size Subarray Sum
原题链接在这里:https://leetcode.com/problems/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.
题解:
双指针维护一个window, 当window 的 sum小于target时一直移动window 的右边, 更新sum.
当sum >= s后一直移动window 左边, 更新sum 和 minLength.
最后返回时看minLength是否被更新过,若被更新过就返回minLength, 没有更新过说明没有符合要求的window, 返回0.
Time Complexity: O(n), array至多走两遍.
Space: O(1).
AC Java:
1 class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 if(nums == null || nums.length == 0 || s <= 0){ 4 return 0; 5 } 6 7 int walker = 0; 8 int runner = 0; 9 int sum = 0; 10 int res = Integer.MAX_VALUE; 11 while(runner < nums.length){ 12 sum += nums[runner++]; 13 while(sum >= s){ 14 res = Math.min(res, runner-walker); 15 sum -= nums[walker++]; 16 } 17 } 18 19 return res == Integer.MAX_VALUE ? 0 : res; 20 } 21 }