滑动窗口(209长度最小的子数组)


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

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

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

暴力解法利用双循环
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int length = 0;//记录当前长度
int result = Integer.MAX_VALUE;//记录最小长度
for (int i = 0; i < nums.length; i++) {
int sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
if (sum >= target) {
length = j - i + 1;
result = result < length ? result : length;
break;
}
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}

}

优化:滑动窗口

所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0;//起始地址
        int sum = 0;
        int result = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];//for循环控制窗口长度
            while (sum >= target) {
                result = Math.min(result, right - left + 1);
                sum -= nums[left++];//每当sum>=target的时候,
              求得序列长度j - i + 1;和result进行比较,让result存入最小值,
              删除起始地址所对应的值,并将起始位置向后挪动一位。
             }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}

相关