[LeetCode] Minimum Size Subarray Sum
2015-05-12 14:19
225 查看
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.
解题思路:
注意这里的subarray是只顺序不可变,故不可以用先排序后选择的方法。
1、暴力滑动窗口法。依次验证窗口大小为1,2,3...的窗口,看看是否有和大于给定值的子数组。时间复杂度为O(n^2),空间复杂度为1
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int size = nums.size();
int len = 1;
while(len<=size){
int sum = 0;
for(int j=0; j<len; j++){
sum += nums[j];
}
if(sum>=s){
return len;
}
int start = 0;
int end = start + len - 1;
while(end + 1<size){
sum -= nums[start];
sum += nums[end+1];
if(sum>=s){
return len;
}else{
start++;
end++;
}
}
len++;
}
return 0;
}
};2、伸缩窗口法。用两个指针start,end,若start和end-1之间的和小于s,end增加,若大于等于s,start增加,然后记录大于等于s时最小的长度。这种办法时间复杂度为O(n),空间复杂度为1。
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int size = nums.size();
if(size==0){
return 0;
}
int minLen = size + 1;
int sum = 0;
int start=0, end=0;
while(end<size){
while(sum<s && end<size){
sum += nums[end];
end++;
}
while(sum>=s){
minLen = min(minLen, end - start);
if(minLen == 1){
return minLen;
}
sum -= nums[start];
start++;
}
}
return minLen==size + 1?0:minLen;
}
};
相关文章推荐
- 【leetcode】Minimum Size Subarray Sum(middle)
- LeetCode Minimum Size Subarray Sum
- LeetCode Minimum Size Subarray Sum
- Minimum Size Subarray Sum -- leetcode
- LeetCode Minimum Size Subarray Sum (最短子序列和)
- Leetcode之Minimum Size Subarray Sum 问题
- [leetcode]Minimum Size Subarray Sum
- [LeetCode] Minimum Size Subarray Sum
- LeetCode刷题【Array】Minimum Size Subarray Sum
- 【leetcode】Array—— Minimum Size Subarray Sum(209)
- leetcode 209: Minimum Size Subarray Sum
- 【LeetCode 209】Minimum Size Subarray Sum
- leetcode -- Minimum Size Subarray Sum -- 重点
- [LeetCode] Minimum Size Subarray Sum 解题思路
- Leetcode NO.209 Minimum Size Subarray Sum
- 开始刷leetcode day14:Minimum Size Subarray Sum
- Minimum Size Subarray Sum —— LeetCode
- Leetcode172: Minimum Size Subarray Sum
- leetcode Minimum Size Subarray Sum
- [leetcode] 209 Minimum Size Subarray Sum