1. 题意
找到最小满足和大于 t a r g e t target target的子数组长度。
长度最小的子数组
2. 题解
2.1 滑动窗口
cpp
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int l = 0;
int sum = 0;
int sz = nums.size();
int ans = INT_MAX;
for (int i = 0; i < sz; ++i) {
sum += nums[i];
if ( sum >= target) {
while ( l <= i && sum >= target) {
sum -= nums[l];
++l;
}
ans = min(ans, i - l + 2);
}
}
return ans == INT_MAX ? 0 : ans;
}
};
2.2 二分
枚举左端点,二分查找满足条件的右端点。
cpp
class Solution {
public:
bool check(int l, int r, vector<int> &nums, int target)
{
int sum = 0;
for (int i = l; i < r + 1; ++i)
sum += nums[i];
return sum >= target;
}
int minSubArrayLen(int target, vector<int>& nums) {
int l = 0;
int sum = 0;
int sz = nums.size();
int ans = INT_MAX;
vector<int> pre(sz + 1, 0);
int preSum = 0;
for (int i = 0;i < sz; ++i) {
preSum += nums[i];
pre[i + 1] = preSum;
}
for (int i = 0;i < sz; ++i) {
int l = i;
int r = sz;
while (l < r) {
int m = ((r - l) >> 1) + l;
// cout << "m"<< m << "," << "sum" << sum << endl;
if ( pre[m + 1] - pre[i] < target)
l = m + 1;
else
r = m;
}
// printf("%d,%d\n", i, l);
if ( l < sz){
ans = min(l - i + 1, ans);
}
}
return ans == INT_MAX ? 0 : ans;
}
};