4.209长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 target

找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0

示例 1:

输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。

示例 2:

输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
//滑动窗口
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0;  //起始位置
        int sum = 0;    //滑动窗口之和
        int subLength = 0;   //滑动窗口长度
        int result = Integer.MAX_VALUE; //  结果,先设置为最大值,后面再比较
        for(int right = 0; right < nums.length; right++){   //  j指向终止位置
            sum += nums[right];    //对起点到终点间的元素求和
            while(sum >= target){  //使用while来保持窗口滑动,如果是if的话,判断一次就结束了
                subLength = right - left + 1;
                result = Math.min(result,subLength);
                sum -= nums[left++];    //sum中的值要减去起始位置滑动的那个值
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}

滑动窗口:

  • for循环指向的是终点位置
  • 使用while判断,因为要保持起始位置的滑动,如果使用if,就只判定一次
  • 什么时候更新?窗口长度满足需求时,因为此时不一定最优,所以迭代
posted @ 2022-10-11 22:26  啦啦米老鼠  阅读(12)  评论(0)    收藏  举报