Minimum Size Subarray Sum
code
i前进,r指针不会退
要记录的值:
1) sum = 0;
2)指针;
3)需要ret的值(最长长度或者最短长度)
class Solution {
public:
/**
* @param nums: a vector of integers
* @param s: an integer
* @return: an integer representing the minimum size of subarray
*/
int minimumSize(vector<int> &nums, int s) {
// write your code here
if(nums.size() == 0)
{
return -1;
}
int ret = INT_MAX;
int r = 0;
int sum = 0;
for(int i = 0; i < nums.size(); i++)
{
while(r < nums.size())
{
if(sum + nums[r] < s)
{
sum += nums[r];
r++;
}
else
{
ret = min(ret, r-i+1);
break;
}
}
sum -= nums[i];
}
return ret == INT_MAX?-1:ret;
}
};
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int n = nums.size();
if(n == 0)
{
return 0;
}
int cur = 0;
int cur_len = 0;
int j = 0;
int rst = INT_MAX;
for(int i = 0; i<n; i++)
{
while(j < n)
{
if(cur >= s)
{
break;
}
cur = cur + nums[j];
j++;
cur_len++;
}
if(cur >= s)
{
rst = min(rst, cur_len);
}
cur = cur - nums[i];
cur_len--;
}
return rst==INT_MAX?0:rst;
}
};