长度最小的子数组
- 给定一个含有 n 个正整数的数组和一个正整数 target 。
- 找出该数组中满足其总和大于等于 target 的长度最小的 连续子数组
- [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
解题思路
使用滑动窗口技巧解决这个问题。
- 可以维护一个滑动窗口,初始时窗口的左右边界都为数组的起始位置,然后移动右边界以扩大窗口,直到窗口内的元素之和大于等于目标值。
- 在扩大窗口的过程中,记录窗口的长度,并不断更新最小长度。
Java实现
public class MinSubArrayLen {
public int minSubArrayLen(int target, int[] nums) {
int left = 0, right = 0;
int sum = 0;
int minLength = Integer.MAX_VALUE;
while (right < nums.length) {
sum += nums[right];
while (sum >= target) {
minLength = Math.min(minLength, right - left + 1);
//缩小窗口,left先赋值,后++
sum -= nums[left++];
}
//扩大窗口
right++;
}
return minLength == Integer.MAX_VALUE ? 0 : minLength;
}
public static void main(String[] args) {
MinSubArrayLen minSubArrayLen = new MinSubArrayLen();
int[] nums1 = {2, 3, 1, 2, 4, 3};
int target1 = 7;
System.out.println("Test Case 1:");
System.out.println("nums: [2, 3, 1, 2, 4, 3], target: 7");
System.out.println("Length of Min Subarray: " + minSubArrayLen.minSubArrayLen(target1, nums1)); // Expected: 2
int[] nums2 = {1, 4, 4};
int target2 = 4;
System.out.println("\nTest Case 2:");
System.out.println("nums: [1, 4, 4], target: 4");
System.out.println("Length of Min Subarray: " + minSubArrayLen.minSubArrayLen(target2, nums2)); // Expected: 1
}
}
时间空间复杂度
- 时间复杂度: 使用滑动窗口遍历一次数组,时间复杂度为 O(n),其中 n 是数组的长度。
- 空间复杂度: 使用了常量级的额外空间,空间复杂度为 O(1)。