【力扣】209. 长度最小的子数组 <滑动窗口>

【力扣】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 = 4, nums = [1,4,4]
输出:1

示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0

提示:
1 <= target <= 1 0 9 10^9 109
1 <= nums.length <= 1 0 5 10^5 105
1 <= nums[i] <= 1 0 5 10^5 105

题解

暴力

class Main {
    
    
    public int minSubArrayLen(int s, int[] nums) {
    
    
        // 最终的结果
        int result = Integer.MAX_VALUE;
        // 子序列的数值之和
        int sum = 0;
        // 子序列的长度
        int subLength = 0;

        // 设置子序列起点为i
        for (int i = 0; i < nums.length; i++) {
    
    
            sum = 0;
            // 设置子序列终止位置为j
            for (int j = i; j < nums.length; j++) {
    
    
                sum += nums[j];
                // 一旦发现子序列和超过了s,更新result
                if (sum >= s) {
    
    
                    // 取子序列的长度
                    subLength = j - i + 1;
                    result = Math.min(result, subLength);
                    break;
                }
            }
        }
        // 如果result没有被赋值的话,就返回0,说明没有符合条件的子序列
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}

滑动窗口:

public class Main {
    
    
    // 滑动窗口
    public int minSubArrayLen(int s, int[] nums) {
    
    
        // 滑动窗口起始位置
        int left = 0;
        // 滑动窗口数值之和
        int sum = 0;
        int result = Integer.MAX_VALUE;
        
        for (int right = 0; right < nums.length; right++) {
    
    
            sum += nums[right];
            // 注意这里使用 while,每次更新 left(起始位置),并不断比较子序列是否符合条件
            while (sum >= s) {
    
    
                result = Math.min(result, right - left + 1);
                //滑动窗口的精髓之处,不断变更 left(子序列的起始位置)
                sum -= nums[left++];
            }
        }
        // 如果result没有被赋值的话,就返回0,说明没有符合条件的子序列
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44033208/article/details/132467051