Skip to content

可变滑动窗口

题目示例:长度最小的子数组

java
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int result = nums.length + 1;
        int i = 0;
        int j = 0;
        int total = 0;
        while (j < nums.length) {
            total += nums[j];
            j++;
            while (total >= target) {
                result = Math.min(result, j - i);
                total -= nums[i];
                i++;
            }
        }
        return result == nums.length + 1 ? 0 : result;
    }
}

核心思路

  1. 右指针 j 不断向右扩大窗口。
  2. 当窗口内满足条件(total >= target)时,左指针 i 开始向右收缩,尝试寻找最小长度。
  3. 持续更新最小结果。

贡献者

The avatar of contributor named as 四季夏目 四季夏目
The avatar of contributor named as Claude Opus 4.5 Claude Opus 4.5

页面历史

最近更新

基于 VitePress 搭建