209. Minimum Size Subarray Sum (Medium)

Given an array of n positive integers and a positive integers, 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]ands = 7,
the subarray[4,3]has the minimal length under the problem constraint.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(nlogn).

Solution 1: 同向Two Pointers O(n); O(1)

思路和76. Minimum Window Substring基本一致

    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int sum = 0; //important
        int left = 0;
        int min = Integer.MAX_VALUE;
        //right pointer moves, left pointer stops until while loop starts
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= s) { //right pointer stops, left pointer moves
                min = Math.min(min, right - left + 1);
                sum -= nums[left++];
            }
        }
        return min == Integer.MAX_VALUE ? 0 : min;
    }

results matching ""

    No results matching ""