209. Minimum Size Subarray Sum

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.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

难度:medium

题目:
给定一个包含正整数的数组和一个正整数s,找出最小长度且元素相连的子数组使得其和大于s. 如果不存在这样的子数组,则返回0.

思路:
滑动伸缩窗口。滑动窗口左边界为start index, 右边界为i, 窗口为[start index, i].

Runtime: 2 ms, faster than 99.88% of Java online submissions for Minimum Size Subarray Sum.

class Solution {
    // O(2n)
    public int minSubArrayLen(int s, int[] nums) {
        int sum = 0, startIdx = 0;
        int minLen = nums.length + 1;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (sum >= s) {
                // shrink window
                while (startIdx <= i && sum >= s) {
                    minLen = Math.min(minLen, i - startIdx + 1);
                    sum -= nums[startIdx++];
                }
            }
        }
        
        return minLen > nums.length ? 0 : minLen;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018026569
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞