题目:
给定一个含有n
个正整数的数组和一个正整数target
。找出该数组中满足其总和大于等于target
的长度最小的连续子数组[numl, num2, ..., numN],
并返回其长度。如果不存在符合条件的子数组,返回 0
。
思想:
前缀和+二分查找
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int len = INT_MAX;
vector<int> sums(nums.size()+1,0);
for(int i = 1;i <= nums.size();i++){
if(i > 1) sums[i] = sums[i - 1] + nums[i - 1];
else sums[i] = nums[i - 1];
}
for(int i = 1;i <= nums.size();i++){
int l = i,r = nums.size() + 1;//1,6
while(l < r){
int mid = (l + r) / 2;//下表是2
if((sums[mid] - sums[i - 1]) < target){
l = mid + 1;
}else if((sums[mid] - sums[i - 1]) >= target){
len = min(len,mid - i + 1);
r = mid;
}
}
}
if(len == INT_MAX){
return 0;
}else{
return len;
}
}
};
//nums = [2 3 1 2 4 3]
int main() {
int n,num;
cin>>n;
//前缀和数组
vector<int> sums(n+1,0);
for(int i = 1;i <= n;i++){
cin>>num;
if(i > 1) sums[i] = sums[i - 1] + num;
else sums[i] = num;
}
// for(int i = 1;i <= n;i++){
// cout<<sums[i]<<endl;
// }
int target;
int len = INT_MAX;
cin>>target;
// cout<<sums[1];
for(int i = 1;i <= n;i++){
int l = i,r = n + 1;//0,6
while(l < r){
int mid = (l + r) / 2;//下表是3
if((sums[mid] - sums[i - 1]) < target){
l = mid + 1;
}else if((sums[mid] - sums[i - 1]) >= target){
len = min(len,mid - i + 1);
// cout<<len<<endl;
r = mid;
}
}
}
if(len == INT_MAX){
cout<<"长度为:"<<0;
}else{
cout<<"长度为:"<<len;
}
return 0;
}