LeetCode每日一题之209.长度最小的子数组

209.长度最小的子数组

方法一:暴力枚举

代码

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int n = nums.length + 1;
        int sum = 0;
        //双重循环枚举所有结果
        for (int i = 0; i < nums.length; i++) {
            sum=0;
            for (int j = i; j < nums.length; j++) {
                sum +=nums[j];
                if (sum>=s && (j - i + 1) < n) {
                    n = j - i + 1;
                    break;
                }
            }
        }
        if (n == nums.length + 1) {
            return 0;
        } else {
            return n;
        }
    }
}

方法二:双指针

代码1

  public int minSubArrayLen1(int s, int[] nums) {
        if (nums.length == 0) {
            return 0;
        } else {  //双指针
            int start = 0;
            int end = 0;
            int best = 0;
            int n = nums.length;
            int sum = nums[0];
            //ans为最小长度暂定为最长+1
            int ans = nums.length + 1;
            while (start <= end) {
                if (sum >= s) {
                	//如果符合条件且子数组长度比ans小就可以更新best;
                    if (end - start + 1 < ans) {
                        ans = end - start + 1;
                        best = ans;
                    }
                    sum -= nums[start];
                    //左指针右移
                    start++;
                } else {
                	//右指针右移
                    end++;
                    if (end >= nums.length) {
                        return best;
                    } else {
                        sum += nums[end];
                    }
                }
            }
            return best;
        }
    }

代码2

    public int minSubArrayLen2(int s, int[] nums) {
        int ans=nums.length+1;
        int start= 0;
        int end = 0;
        int sum = 0;
        while(end<nums.length){
            sum+=nums[end];
            while (sum>=s){
                 ans = Math.min(ans,end-start+1);
                 sum-=nums[start];
                 start++;
            }
            end++;
        }
        return ans==nums.length+1?0:ans;
    }

注意:代码二比较简短,但是运行时间比较长

你可能感兴趣的:(LeetCode,Java)