leetcode 209

长度最小的子数组

Posted by Static on June 28, 2020

题目链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum/

题目描述


分析

1. 双循环

2. 循环+指针


代码实现

public enum Q209 {
    instance;
    public int minSubArrayLen(int s, int[] nums) {
        int minL=Integer.MAX_VALUE;
        for(int i=0;i<nums.length;i++){
            int sum=0;
            for(int p=i;p<nums.length;p++){
                if(minL==1)return 1;
                // 累加
                sum+=nums[p];
                // 之和大于等于s,赋值
                if(sum>=s){
                    int e=p-i+1;
                    minL=minL>e?e:minL;
                    break;
                }
            }
        }
        return minL==Integer.MAX_VALUE?0:minL;
    }

    public int minSubArrayLen1(int s, int[] nums) {
        int minL=Integer.MAX_VALUE;
        for(int i=0;i<nums.length;i++){
            int sum=0;
            for(int j=i;j>=0;j--){
                if(minL==1)return 1;
                sum+=nums[j];
                if(sum>=s){
                    int e=i-j+1;
                    minL=minL>e?e:minL;
                    break;
                }
            }
        }
        return minL==Integer.MAX_VALUE?0:minL;
    }

    public static void main(String[] args) {
        // assert 2
        System.out.println(Q209.instance.minSubArrayLen(7,new int[]{2,3,1,2,4,3}));
        System.out.println(Q209.instance.minSubArrayLen1(7,new int[]{2,3,1,2,4,3}));
    }
    
}

The real life is a life of thought and soul. (Russia) Chernyshevski

真正的生活是思想和灵魂的生活 – [俄] 车尔尼雪夫斯基