-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path209.cpp
44 lines (43 loc) · 1.09 KB
/
209.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//12ms; better than 86% solutions
//time complexity:O(N);
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
if(nums.size()==0)
return 0;
int start=0,end=0,sum=nums[0],ans=INT_MAX;
while(end<nums.size())
{
if(start==end && sum==s)
{
return 1;
}
else if(sum<s)
{
if(end<nums.size()-1)
end++,sum+=nums[end];
else if(ans==INT_MAX)
return 0;
else
return ans;
}
else if(sum>s)
{
ans=min(ans,end-start+1);
if(ans==1)
return 1;
sum-=nums[start],start++;
}
else if(sum==s)
{
ans=min(ans,end-start+1);
sum-=nums[start],start++;
}
}
if(ans==INT_MAX)
return 0;
return ans;
}
};