自学内容网 自学内容网

力扣 209.长度最小的子数组

一、长度最小的子数组

在这里插入图片描述

二、解题思路

采用滑动窗口的思路,详细见代码。

三、代码

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length, left = 0, right = 0, sum = 0;
        int ans = n + 1; 
        for (right = 0; right < n; right ++) { //right 遍历数组
            sum += nums[right];
            while (sum - nums[left] >= target) { // 当子数组的和大于等于 target 时,开始从左收缩数组
                sum -= nums[left];
                left++;
            }
            if (sum >= target) { // 当 ringht 处于数组前边部分时,可能子数组和还没有达到 target值,达到后再更新ans
                ans = Math.min(ans, right - left + 1);
            }
        }
        return ans <= n ? ans : 0;
    }
}


原文地址:https://blog.csdn.net/J_pluto/article/details/142425694

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!