标签:leetcode minimum size subarra
题目:
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.
分析:一开始我采用的是LIS(longest increased sequence)中的最长递增子序列中的动态规划的思想,能通过,但是时间复杂度为O(N
^2);;;第二种方法是采用双指针+滑动窗口的思想,时间复杂度为O(N), 严格意义上说是2N,,比如 [1,2,3,15,3,4,5,15] s=14,,,只有在15处将前面的元素又重新加了一遍,故为2N
代码:
class Solution {
public:
// 法一
/*int minSubArrayLen(int s, vector<int>& nums) {
int result = nums.size();
bool flag = false;
for(int i = 0; i < nums.size(); i++){
if(nums[i] >= s) return 1;
int sum = nums[i];
for(int j = i-1; j >= 0; j--){
sum += nums[j];
if(sum >= s){
result = min(result, i-j+1);
flag = true;
break;
}
}
}
if(flag)return result;
return 0;
}*/
int minSubArrayLen(int s, vector<int>& nums) { // 滑动窗口的形式+双指针
int result = nums.size()+1;
int frontPoint = 0, sum = 0;
for(int i = 0; i < nums.size(); i++){
sum += nums[i];
while(sum >= s){
result = min(result, i - frontPoint + 1);
sum -= nums[frontPoint++];
}
}
return result == (nums.size()+1) ? 0:result;
}
};标签:leetcode minimum size subarra
原文地址:http://blog.csdn.net/lu597203933/article/details/46389491