您的位置:首页 > 其它

209. Minimum Size Subarray Sum

2017-07-07 15:44 357 查看
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时的最小
4000
值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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: