找出长度最小的连续子数组

刷题小能手之数组篇(4)

力扣链接

package arrayAlgorithm;

/**
 * 给定一个含有 n 个正整数的数组和一个正整数 target 。
 * <p>
 * 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
 */
public class MinimumLengthSubArray {
    public static int subArr(int[] arr, int target) {
        /**
         * Java中提供了三个特殊的浮点数值:正无穷大、负无穷大、非数,用于表示溢出和出错。
         *
         * 正无穷大:用一个正数除以0将得到一个正无穷大,通过Double或Float的POSITIVE_INFINITY表示。
         *
         * 负无穷大:用一个负数除以0将得到一个负无穷大,通过Double或Float的NEGATIVE_INFINITY表示。
         *
         * 非数:0.0除以0.0或对一个负数开放将得到一个非数,通过Double或Float的NaN表示。
         *
         * 所有的正无穷大的数值都是相等的,所有的负无穷大的数值都是相等;而NaN不与任何数值相等,甚至和NaN都不等。
         */
        int endLength = 9999;  // 将最短子数组长度初始化为无穷大
        System.out.println("endLength: " + endLength);
        int nowLength = 0; // 记录当前数组长度
        int sum = 0;  // 初始化子数组和
        int i = 0;
        for (int j = 0; j < arr.length; j++) {
            sum += arr[j]; // 计算子数组和

            while (sum >= target) {
                nowLength = j - i + 1;
                endLength = Math.min(nowLength, endLength);
//                endLength = nowLength < endLength ? nowLength : endLength;
                sum -= arr[i++];

            }
        }

        return endLength == 9999 ? 0 : endLength;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};
        System.out.println(subArr(nums, 7));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值