您的位置:首页 > 其它

leetcode@ [209]Minimum Size Subarray Sum

2015-11-01 15:19 351 查看
https://leetcode.com/problems/minimum-size-subarray-sum/

Given an array of n positive integers and a positive integer s, find the minimal length of a 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.

class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
vector<int> vec = nums;

for(int i=1;i<nums.size();++i){
nums[i]+=nums[i-1];
}

int minLen = numeric_limits<int>::max();
for(int i=0;i<nums.size();++i){
int low = i, high = nums.size()-1, mid;
while(low < high){
mid = (low+high)/2;
if(nums[mid]-nums[i]+vec[i] < s)  low = mid+1;
else high = mid;
}
if(nums[low]-nums[i]+vec[i]>=s && low-i+1<minLen) minLen = low-i+1;
}

if(minLen == numeric_limits<int>::max()) return 0;
else return minLen;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: