给定一个含有 n
个正整数的数组和一个正整数 target
。
找出该数组中满足其总和大于等于 target
的长度最小的 连续
子数组
[numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回 0
。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3]
是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4] 输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1] 输出:0
解释:
- 首先判断数组是否为空,如果为空则直接返回0。
- 定义两个指针
start
和end
,分别表示滑动窗口的起始位置和结束位置。同时定义变量sum
用于记录当前滑动窗口内的元素和,以及变量minLen
用于记录满足条件的最小子数组长度。 - 使用for循环遍历数组,每次将
nums[end]
加入到sum
中。 - 当
sum
大于等于target
时,进入内层的while循环。在循环内部:- 更新
minLen
为当前滑动窗口的长度end - start + 1
和minLen
的较小值。 - 从
sum
中减去nums[start]
,并将start
指针向右移动,缩小滑动窗口的大小。 - 重复这个过程,直到
sum
小于target
为止。
- 更新
- 最后,如果
minLen
的值没有被更新,说明不存在满足条件的子数组,返回0;否则返回minLen
的值。
需要注意的点:
- 在计算子数组长度时,使用
end - start + 1
而不是end - start
,因为数组的下标是从0开始的。 - 在更新
minLen
时,使用min(minLen, end - start + 1)
来获取当前滑动窗口长度和之前的最小长度的较小值。 - 在返回结果时,使用三元运算符
minLen == INT_MAX ? 0 : minLen
来判断是否找到了满足条件的子数组。如果minLen
的值没有被更新,说明不存在满足条件的子数组,返回0;否则返回minLen
的值。
Explanation:
- First, check if the array is empty. If it is, return 0.
- Define two pointers,
start
andend
, representing the start and end positions of the sliding window. Also, define a variablesum
to keep track of the sum of elements within the current sliding window, and a variableminLen
to store the minimum length of the subarray that satisfies the condition. - Use a for loop to iterate through the array. In each iteration, add
nums[end]
tosum
. - When
sum
is greater than or equal totarget
, enter the inner while loop. Inside the loop:- Update
minLen
to be the smaller value between the current sliding window lengthend - start + 1
andminLen
. - Subtract
nums[start]
fromsum
and move thestart
pointer to the right, shrinking the size of the sliding window. - Repeat this process until
sum
becomes less thantarget
.
- Update
- Finally, if the value of
minLen
has not been updated, it means no subarray satisfies the condition, so return 0. Otherwise, return the value ofminLen
.
Points to note:
- When calculating the length of the subarray, use
end - start + 1
instead ofend - start
because array indices start from 0. - When updating
minLen
, usemin(minLen, end - start + 1)
to get the smaller value between the current sliding window length and the previous minimum length. - When returning the result, use the ternary operator
minLen == INT_MAX ? 0 : minLen
to check if a subarray satisfying the condition was found. If the value ofminLen
has not been updated, it means no subarray satisfies the condition, so return 0. Otherwise, return the value ofminLen
.:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
if (nums.size() == 0) return 0;
int start = 0, sum = 0;
int minLen = INT_MAX;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
while (target <= sum) {
//cout << "yeah" << "target : " << target << "sum: " << sum<< endl;
minLen = min(minLen, i - start);
sum -= nums[start];
start++;
}
}
return minLen == INT_MAX ? 0 : minLen;
}
};