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.

[分析] 应用滑动窗口法,实现时主要考虑1)窗口何时滑动或者说窗口的左边界何时更新? 2) 最小窗口是在滑动过程中比较而得,又何时更新该值? 窗口内各元素加和要保持小于给定的s, 一旦不小于时就是滑动窗口和更新minSize的时机,向右滑动窗口直到窗口内元素加和小于s。

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        int N = nums.length;
        int start = 0;
        int minSize = N + 1;
        int sum = 0;
        for (int i = 0; i < N; i++) {
            sum += nums[i];
            while (sum >= s) {
                minSize = Math.min(minSize, i - start + 1);
                if (minSize == 1) return 1;
                sum -= nums[start++];
            }
        }
        return minSize <= N ? minSize : 0;
    }
}

你可能感兴趣的:(LeetCode)