leetcode 209 滑动窗口

124 阅读1分钟

//给定一个含有 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 <= 109 
// 1 <= nums.length <= 105 
// 1 <= nums[i] <= 105 
// 
//
// 
//
// 进阶: 
//
// 
// 如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。 
// 
// Related Topics 数组 双指针 二分查找 
// 👍 627 👎 0


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        //窗口移动初始位置控制
        int j = 0;
        // 第二个指针,用于控制窗口向前移减去最后一位
        int i = 0;
        //存数累加和
        int total = 0;
        //存最小窗口数
        int res = nums.length + 1;
        //j当累加未满足要求时,控制数量累加
        while(j < nums.length){
            total += nums[j];
            j++;
            //当满足条件,有两种情况满足条件,第一种是向前移的累加,第二种是基于第一种满足前提但数又远远大于的最后一位减
            //控制窗口前移,同时减掉窗口最后一位
            while (total>=target){
                res = Math.min(res,j-i);
                    //减去前面最后一位
                total = total - nums[i];
                    i = i+1;
            }

        }
        //如果全部不满足,res默认等一开始赋的nums.length + 1
        return res == nums.length + 1 ? 0 : res ;
    }
}
//leetcode submit region end(Prohibit modification and deletion)