Given an array of positive integers nums and a positive integer target, return the minimal length of a
subarray
whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4] Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int sum = 0;
int ans = 0;
int i = 0;
int result = INT32_MAX;
for(int j = 0;j < nums.size();j ++){
sum+=nums[j];
while(sum>= target){
result = min(j - i + 1,result);
sum -= nums[i];
i++;
}
}
if(result == INT32_MAX)
return 0;
return result;
}
};
这篇文章讨论了如何找到给定正整数数组中,满足和大于或等于目标值的最小子数组长度。通过迭代和优化,Solution类提供了求解该问题的函数。
1231

被折叠的 条评论
为什么被折叠?



