Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s
= 7,
the subarray [4,3] has the minimal length under the
problem constraint.
题意:给一个数组和值s,求数组里连续子序列和>=s,并使得这个连续子序列长度最小。
思想:由于是连续的子序列 可以定义2个指针start,end,tempsum为数组[start....end]之和的值,min为所有tempsum>=s的最小值
移动end或start指针
若数组[start....end]之和<s 那么指针end++;
若数组[start....end]之和>s 判断min是否是最小值 然后指针start++;
找到tempsum>=s时的最小值min
C++ AC代码:Time O(n) Space O(1) 这次有些判断不到位,导致代码复杂度比较高,还需加强训练!!!
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int len = nums.size();
if(len<=0) return 0;
int min = len;
int b = 0;
int e = 0;
int tempsum = nums[0];
while(b<=e&&e<len){
if(e==b&&nums[e]>=s)
return 1;
else if(e==b&&nums[e]<s){
e++;
tempsum +=nums[e];
}
else if(e!=b&&tempsum>=s){
min = min<(e-b+1)?min:(e-b+1);
if(e==len-1&&tempsum-nums[b]<s)
break;
tempsum-=nums[b];
b++;
}else if(e!=b&&tempsum<s){
e++;
if(e==len)
break;
tempsum +=nums[e];
}
}
min = (tempsum>=s||min!=len)?min:0;
return min;
}
};

本文介绍了一种算法,用于寻找给定数组中满足特定条件的最短连续子数组。通过移动双指针的方式,实现时间复杂度O(n)和空间复杂度O(1),并附带了详细的C++代码实现。
1230

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



