Passion and Patience

Work Hard, Play Hard

导航

Leetcode 长度最小的子数组

Day 13 第一题

超出运行时间,两层循环
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        
        if(Arrays.stream(nums).sum()<target){
            return 0;
        }

        int minSubArrayLen = nums.length;

        OUT:
        for(int p1 = 0;p1<nums.length;p1++){
            int count = 1, p2 = p1+1, sum = nums[p1];

            while(sum<target){

                if(p2>=nums.length){
                    continue OUT;
                } 
                sum += nums[p2++];
                count++;             
            }

            minSubArrayLen = Math.min(minSubArrayLen,count);
        }

        return minSubArrayLen;
    }
}
代码随想录:滑动窗口解法
class Solution {

    // 滑动窗口
    public int minSubArrayLen(int s, int[] nums) {
        int left = 0;
        int sum = 0;
        int result = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= s) {
                result = Math.min(result, right - left + 1);
                sum -= nums[left++];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}

posted on 2024-03-29 14:19  安静的聆  阅读(6)  评论(0编辑  收藏  举报