day3

  1. [0209长度最小的子数组]

    class Solution {
        public int minSubArrayLen(int target, int[] nums) {
            int numsLength = nums.length;
            for (int k = 0; k <= numsLength-1; k++){
                int sum = 0;
                int i = 0;
                int j = i + k;
                while (j <= numsLength-1){
                    for(int temp = i; temp <= j; temp++){
                        sum = sum + nums[temp];
                    }      
                    if (sum >= target)
                        return k+1; 
                    i++;
                    j++;
                }
            }
            return 0;
        }
    }
    
    • 确实看到提示说是用滑动窗口代替两个for循环,但调节滑动窗口的起始位置这部分精髓代码比较蒙''''''''''
    class Solution {
        public int minSubArrayLen(int target, int[] nums) {
            int numsLength = nums.length; 
            int i = 0; 
            int sum = 0;
            for (int j = 0; j <= numsLength-1; j++){
                sum += nums[j] 
                if (sum >= target){
                    i ++;
                    sum = sum - nums[i-1];  
                }
            }        
            }
            return 0;
        }
    }
    
    • 窗口可能大小subLength,窗口实际大小result,都还没定义出来
    class Solution {
        public int minSubArrayLen(int target, int[] nums) {
            int numsLength = nums.length; 
            int result = Integer.MAX_VALUE;
            int subLength = 0;
            int i = 0; 
            int sum = 0;
            for (int j = 0; j <= numsLength-1; j++){
                sum += nums[j]; 
                while (sum >= target){                
                    subLength = ( j - i + 1 );
                result = result < subLength ? result : subLength;
                sum = sum - nums[i];  
                i ++;
            }
        }        
        return result == Integer.MAX_VALUE ? 0 : result;
    }
    }
    
  • 里层用for和用while完全不一样,for只循环一次,while循环多次
    明天继续:)
posted @ 2022-10-28 21:45  跬步瑶  阅读(24)  评论(0)    收藏  举报