LeetCode 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.

题意:给出一个由正整数组成的数组,求其和为s的最小子数组长度

思路:先计算和>=s的下标,然后减去最左边的下标,直到其和小于s,这时,更新最小子数组长度

代码如下:

class Solution {
     public int minSubArrayLen(int s, int[] nums)
     {
         int res = nums.length;
         int lo = 0, hi = 0;
         int sum = 0;
         boolean hasMin = false;

         while (hi < nums.length)
         {
             while (sum < s && hi < nums.length)
             {
                 sum += nums[hi++];
             }

             while (sum - nums[lo] >= s)
             {
                 sum -= nums[lo++];
             }
             if (!hasMin && sum >= s) hasMin = true;
             res = Math.min(res, hi - lo);
             sum -= nums[lo++];
         }


         return hasMin ? res : 0;
     }
}

你可能感兴趣的:(LeetCode Minimum Size Subarray Sum)