# C++ 6ms solution sliding window

• Any elegant way to replace do-while loop ? Look like it's the most fitting....

``````class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int num_len= nums.size();
int left=0, right=0, total=0, min_len= num_len+1;
while (right < num_len) {
// move right silder forward till total >= s
do { total += nums[right++]; } while (right<num_len && total< s);
// move left slider forward while maintaining total >= s
while (left<right && total-nums[left]>=s) total -= nums[left++];
// record if it's the minimum
if (total>=s && min_len> right- left)
min_len= right- left;
}
return min_len<=num_len ? min_len: 0;
}
};``````

• Nice to know this is sliding window algorithm, thanks.

• Great idea! Very easy to understand and to prove it is `O(n)`.

• ``````int minSubArrayLen(int s, int* nums, int n) {
if (n < 1)
{
return 0;
}

int result = n+1;

int sum = 0;
int left = 0;
int right = 0;

while (right < n)
{
sum += nums[right];
if (sum >= s)
{
while (sum >= s)
{
sum -= nums[left];
left++;
}
// left-1...right保存了此时最短的和大于s的序列

int temp = right-left+2;
if (temp < result)
{
result = temp;
}
}
right++;
}

if (result > n)
{
return 0;
}

return result;
}``````