您的位置:首页 > 其它

209. Minimum Size Subarray Sum

2017-06-20 16:32 344 查看
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.

题意:与目标相等的最短子序列。用两个指针从头开始,当和sum小于s时,右指针+1,当和大于等于s,减去左指针的数,左指针+1

class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int sz = nums.size();
if(sz == 0) return 0;
int Min = 0;
int sum = nums[0];
int l = 0, r = 0;
while(l <= r){
if(sum >= s){
if(Min == 0) Min = r - l + 1;
else Min = Min > (r - l + 1) ? (r - l + 1) : Min;
sum -= nums[l];
++l;
} else {
if(r < sz - 1){
++r;
sum += nums[r];
} else {
break;
}
}
}
return Min;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: