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

click to show more practice.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases. 

Hide Tags
  Array Two Pointers Binary Search  

链接: http://leetcode.com/problems/minimum-size-subarray-sum/

题解:

首先想到滑动窗口sliding window,从0开始累加,当和Sum大于等于S的时候再从左侧减小窗口,继续进行判断。

Time Complexity - O(n),Space Complexity - O(1)

public class Solution {

    public int minSubArrayLen(int s, int[] nums) {      //sliding window

        if(nums == null || nums.length == 0 || s <= 0)

            return 0;

        int sum = 0, minLen = Integer.MAX_VALUE, left = 0;

        

        for(int right = 0; right < nums.length; right++){

            sum += nums[right];

            

            while(sum >= s){

                minLen = Math.min(right - left + 1, minLen);

                sum -= nums[left++];

            }

        }

        

        return minLen != Integer.MAX_VALUE ? minLen : 0;

    }

}

 

测试:

Reference:

你可能感兴趣的:(array)