1. 程式人生 > >[leetcode]209. Minimum Size Subarray [email protecte

[leetcode]209. Minimum Size Subarray [email protecte

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

Credits:


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

這道題可以使用滑動視窗的解法,很簡潔,使用sum來記錄之前的計算結果

package day0304.array;

/**
 * Given an array of n positive integers and a positive integer s,
 * find the minimal length of a contiguous subarray of which the sum ≥ s.
 * If there isn't one, return 0 instead.
 * <p>
 * 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.
 */
public class P209_MinimumSizeSubarraySum {

    /*
    滑動視窗解法
     */
    public int minSubArrayLen(int s, int[] nums) {
        int l = 0, r = -1;//前閉後閉 如果r初始化為0的話,就包含了第一個元素
        int sum = 0;
        int res = nums.length + 1;

        while (l < nums.length) {

            if (r + 1 < nums.length && sum < s)
                sum += nums[++r];
            else//當r到右邊界後,l會一直增加到邊界值
                sum -= nums[l++];

            if (sum >= s)
                res = Math.min(res, r - l + 1);

        }

        if (res == nums.length + 1)
            return 0;

        return res;
    }
}