Leetcode 209. 长度最小的子数组(Minimum size subarray sum)

Ahci / 2023-08-13 / 原文

题目链接

给定一个含有 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

提示:

1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105

思路

暴力解法:
使用两个for循环, 时间复杂度为O(n^2), 不过使用暴力解法在Leetcode上提交已经超时了.

滑动窗口:
就是使用两个指针不断变动起始位置和结束位置从而得出想要的结果.
在暴力解法中, 第一个for循环代表起始位置, 第二个for循环代表终止位置, 而在滑动窗口中只使用一个for循环, 这个循环代表的是滑动窗口的终止位置.
而当窗口值大于目标值了, 起始位置就要向前移动了. 再向前移动时让窗口中的值减去自己所在的位置的值, 并计算窗口大小, 直到窗口中的值小于目标值,

代码实现

滑动窗口:

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int sum = 0;
        int count = Integer.MAX_VALUE;
        for(int left = 0, right = 0; right < nums.length; right++) {
            sum += nums[right];
            while(sum >= target) {
                count = Math.min(count, right - left + 1);
                sum -= nums[left++];
            }
        }
        return count == Integer.MAX_VALUE ? 0 : count;
    }
}