[Leetcode] Minimum Size Subarray Sum 最短子串和

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

双指针

复杂度

时间 O(N) 空间 O(1)it

思路

咱们用两个指针维护一个窗口,保证这个窗口的内的和是小于目标数的。若是新来的数加上后,和大于目标,则比较下当前窗口长度和最短窗口长度,窗口左边界右移。若是和仍小于目标数,则将窗口右边界右移。注意这里退出的条件,右边界是小于等于长度,由于咱们窗口到了最右侧时,还须要继续左移左边界来看有没有更优的解法。另外,若是左边界大于右边界时,说明最短子串的长度已经小于等于1,咱们就不用再查找了。io

注意

循环的判断条件是right <= nums.length && left <= rightclass

代码

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if(nums.length == 0) return 0;
        int left = 0, right = 0, sum = 0, minLen = nums.length + 1;
        while(right <= nums.length && left <= right){
            if(sum < s){
                // 当右边界等于长度时,咱们要多等一轮,等待左边界左移,这时候不能加
                if(right < nums.length){
                    sum += nums[right];
                }
                right++;
            } else {
                // 当和大于等于目标时,检查长度并左移边界
                minLen = Math.min(minLen, right - left);
                sum -= nums[left];
                left++;
            }
        }
        return minLen <= nums.length ? minLen : 0;
    }
}
相关文章
相关标签/搜索