给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
1 2 3
| 输入:target = 7, nums = 输出:2 解释:子数组 是该条件下的长度最小的子数组。
|
示例 2:
1 2
| 输入:target = 4, nums = [1,4,4] 输出:1
|
示例 3:
1 2
| 输入:target = 11, nums = [1,1,1,1,1,1,1,1] 输出:0
|
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
进阶:
- 如果你已经实现
O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。
解题思路
双指针法
移动右指针,并加入sum
如果满足sum >= target,则移动尝试缩小左区间
否则,继续移动右区间
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int minSubArrayLen(int target, int[] nums) { int left = 0; int right = 0; int sum = 0; int min_len = Integer.MAX_VALUE; while(right < nums.length){ sum += nums[right]; if(sum >= target){ min_len = Math.min(min_len, right - left + 1); while(sum - nums[left] >= target){ sum -= nums[left]; left ++; min_len = Math.min(min_len, right -left +1); } } right ++; } return min_len == Integer.MAX_VALUE? 0 : min_len; } }
|
时间复杂度:$O(n)$
空间复杂度:$O(1)$