Minimum Size Subarray Sum
程序员文章站
2022-07-15 17:46:25
...
1. 解析
题目大意,在保证连续子序列的和不小于目标值的情况下,求解子序列的最短长度
2. 分析
序列中的元素都是大于0的,即都是递增,所以,我们可以设置left和right左右指针,right指针往前移动,sum记录当前[left, right]范围的累和,当sum > 目标值s,缩小窗口[left, right]的范围,即left往右移动,直到sum < 目标值,则当前子序列的长度就是right-left;继续往下搜索,重新获取窗口[left, right]的子序列长度,更新最小值即可
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int left = 0, right = 0, res = nums.size() + 1;
int cur = 0;
int sum = 0;
while (right < nums.size()){
while (right < nums.size() && sum < s){ //扩大窗口
sum += nums[right++];
}
while (sum >= s){ //缩小窗口
res = min(res, right-left);
sum -= nums[left++];
}
}
return res == nums.size() + 1 ? 0 : res;
}
};
上一篇: 785. 判断二分图
推荐阅读
-
HK Maximum Subarray Sum
-
LintCode 139. Subarray Sum Closest
-
Minimum Size Subarray Sum
-
Minimum Size Subarray Sum
-
lintcode-44. Minimum Subarray
-
LeetCode C++ 599. Minimum Index Sum of Two Lists【Hash Table】简单
-
LeetCode 560 Subarray Sum Equals K (hash)
-
[LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
-
Leetcode0523--Continuous Subarray Sum 连续和倍数
-
UVA - 10791 Minimum Sum LCM(质因数分解)