【LeetCode-中等题】209. 长度最小的子数组

题目

在这里插入图片描述

方法一:滑动窗口:

参考图解动画:长度最小的子数组
在这里插入图片描述

class Solution {
    
    
//方法一:滑动窗口
    public int minSubArrayLen(int target, int[] nums) {
    
    
      int n = nums.length;
      if(n == 0) return 0;
      int left = 0;
      int res = Integer.MAX_VALUE;
      int sum = 0;
     for(int  right = 0; right<n; right++){
    
    
         sum = sum +nums[right];
         while(sum >= target){
    
    
              res = Math.min(res, right - left + 1);
             sum -= nums[left];
              left++;
         }
     }
       return res== Integer.MAX_VALUE ? 0 : res;
    }
}
class Solution {
    
    
//方法一:滑动窗口
    public int minSubArrayLen(int target, int[] nums) {
    
    
      int n = nums.length;
      if(n == 0) return 0;
      int left = 0;
      int res = Integer.MAX_VALUE;
      int right = 0;
      int sum = 0;
      while(right < n){
    
    
          sum += nums[right];
          if(sum < target) right++;
          else if(sum >= target){
    
    
              res = Math.min(res,right - left + 1);
              sum = sum - nums[left] -nums[right];
              left++;
          }
      }
       return res== Integer.MAX_VALUE ? 0 : res;
    }
}

两种方式都可以 一定要画图理解

方法二:

猜你喜欢

转载自blog.csdn.net/weixin_45618869/article/details/132805289