刷题小能手之数组篇(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));
}
}