【算法】数组-长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。

示例:

  • 输入:s = 7, nums = [2,3,1,2,4,3]
  • 输出:2
  • 解释:子数组 [4,3] 是该条件下的长度最小的子数组。

提示:

  • 1 <= target <= 10^9
  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

本题对应力扣209题

首先是暴力求解

复制代码
public class MinimumSubArrayLength {
    public static int minSubArrayLen(int s, int[] nums) {
        int result = Integer.MAX_VALUE; // 最终的结果
        int sum = 0; // 子序列的数值之和
        int subLength = 0; // 子序列的长度
        for (int i = 0; i < nums.length; i++) { // 设置子序列起点为i
            sum = 0;
            for (int j = i; j < nums.length; j++) { // 设置子序列终止位置为j
                sum += nums[j];       
                if (sum >= s) { // 一旦发现子序列和超过了s,更新result
                    subLength = j - i + 1; // 取子序列的长度
                    result = Math.min(result, subLength);
                    break; // 因为我们是找符合条件最短的子序列,所以一旦符合条件就break
                }
            }
        }
        // 如果result没有被赋值的话,就返回0,说明没有符合条件的子序列
        return result == Integer.MAX_VALUE ? 0 : result;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};
        int s = 7;
        int result = minSubArrayLen(s, nums);
        System.out.println("输出:" + result);
    }
}

第二种方法是滑动求解,目的是用一层循环代替两层循环,降低复杂度

复制代码
public class MinimumSubArrayLength {
    public static int minSubArrayLen(int s, int[] nums) {
        int sum = 0,left = 0;
        int result = Integer.MAX_VALUE;
        for(int right = 0;right<nums.length;right++){
            sum = sum + nums[right];
            while(sum >= s){ //要持续滑动,不能只判断一次就停止了
                result = Math.min(result, right - left + 1);
                sum = sum - nums[left];
                left++;

            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};

        int s = 7;
        int result = minSubArrayLen(s, nums);
        System.out.println("输出:" + result);
    }
}
相关推荐
叶 落3 分钟前
ubuntu 安装 JDK8
java·ubuntu·jdk·安装·java8
爱学习的白杨树6 分钟前
Sentinel介绍
java·开发语言
Frankabcdefgh11 分钟前
Python基础数据类型与运算符全面解析
开发语言·数据结构·python·面试
XW13 分钟前
java mcp client调用 (modelcontextprotocol)
java·llm
kaiaaaa16 分钟前
算法训练第十五天
开发语言·python·算法
Coovally AI模型快速验证30 分钟前
SLAM3R:基于单目视频的实时密集3D场景重建
神经网络·算法·3d·目标跟踪·音视频
Once_day1 小时前
代码训练LeetCode(29)最后一个单词的长度
算法·leetcode·c
凌肖战1 小时前
力扣上C语言编程题:最大子数组和(涉及数组)
c语言·算法·leetcode
蒟蒻小袁1 小时前
力扣面试150题--除法求值
算法·leetcode·面试
客卿1231 小时前
力扣hot100--反转链表
算法·leetcode·链表