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.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
注意:求的是连续子数组
1.o(n)
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int numsSize = nums.size(); int i=-1,j=0; int sum=0; int minLen = numsSize+1; while(i<j){ if(sum<s){ if(j>=numsSize){ break; } sum+=nums[j++]; }else if(sum>=s){ minLen = min(minLen,j-i-1); sum-=nums[++i]; } } return minLen==numsSize+1 ? 0:minLen; } };
2.o(nlgn)
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int numsSize = nums.size(); int low = 0,high=numsSize+1; while(low<high){ int mid = low+(high-low)/2; int sum = 0; for(int i=0;i<numsSize;i++){ sum+=nums[i]; if(i>=mid){ sum-=nums[i-mid]; } if(sum>=s){ break; } } if(sum>=s){ high = mid; }else{ low = mid+1; } } return low==numsSize+1 ? 0:low; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记