class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size();
int sht = INT_MAX;
vector<int> vi;
int sum = 0;
vi.push_back(sum);
for(int i=0;i<n;i++){
sum+=nums[i];
vi.push_back(sum);
}
/*复杂度过高超时了
for(int i=0;i<vi.size();i++){
if(vi[i]>=target){
int st = 0;
while(vi[i]-vi[st]>=target){
++st;
}
sht = i-st+1<sht?i-st+1:sht;
}
}
*/
//二分搜索降低复杂度
for (int i = 1; i <= n; i++) {
int tar = target + vi[i - 1];
auto bound = lower_bound(vi.begin(), vi.end(), tar);
if (bound != vi.end()) {
sht = min(sht, static_cast<int>((bound - vi.begin()) - (i - 1)));
}
}
return sht==INT_MAX?0:sht;
}
};
剑指 Offer II 008. 和大于等于 target 的最短子数组
最新推荐文章于 2024-08-24 21:53:36 发布