leetcode 209.长度最小的子数组

文章介绍了如何使用滑动窗口和前缀和结合二分查找的方法来解决寻找数组中和大于特定值的最小子数组长度的问题。提供了两种Java实现方案,一种是基于滑动窗口的单循环方法,另一种是利用前缀和构建新数组后进行二分查找的策略。
摘要由CSDN通过智能技术生成

力扣链接:力扣

思路

长度等于target的子数组有多个,想要确定最小的需要使用Math.min来更新最小数。初始化result = Integer.MAX_VALUE。

滑动窗口

  • 所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果
  • 在暴力解法中,是一个for循环滑动窗口的起始位置,一个for循环为滑动窗口的终止位置,用两个for循环 完成了一个不断搜索区间的过程。
  • 滑动窗口只用一个for循环,那么这个循环的索引,一定是表示 滑动窗口的终止位置

前缀和+二分查找

  • 通过求取前缀和保存在新数组中,因为题目已知数组中为正整数,所以新数组中为单调不减的正整数
  • 在前缀和中,由后面的数减去前面的数算出子数组和,就可以通过遍历新数组查询target加上数组元素的和是否在新数组中。

Java

滑动窗口

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int result = Integer.MAX_VALUE;
        int i = 0, sum = 0;
        for(int j = 0; j < nums.length; j++) {
            sum += nums[j];
            while(sum >= target) {
                result = Math.min(result, j - i + 1);
                sum -= nums[i++];
            }
        }
        return result = result == Integer.MAX_VALUE ? 0 : result;
    }
}

前缀和+二分查找

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return 0;
        }
        int ans = Integer.MAX_VALUE;
        int[] sums = new int[n + 1]; 
        // 为了方便计算,令 size = n + 1 
        // sums[0] = 0 意味着前 0 个元素的前缀和为 0
        // sums[1] = A[0] 前 1 个元素的前缀和为 A[0]
        // 以此类推
        for (int i = 1; i <= n; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }
        for (int i = 1; i <= n; i++) {
            int target = s + sums[i - 1];
            int bound = Arrays.binarySearch(sums, target);
            if (bound < 0) {
                bound = -bound - 1;
            }
            if (bound <= n) {
                ans = Math.min(ans, bound - (i - 1));
            }
        }
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值