-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
209.cpp
51 lines (50 loc) · 1.64 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
45
46
47
48
49
50
51
__________________________________________________________________________________________________
sample 4 ms submission
auto opt = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
return 0;
}();
struct Solution {
int minSubArrayLen(int s, std::vector<int> &nums) {
const int N = nums.size();
const int target = s;
int sum = 0, left = 0, right = 0;
int minlen = N + 1;
for (; right < N; ++right) {
sum += nums[right];
if (sum >= target) {
for (; left <= right && sum >= target; ++left) {
minlen = std::min(minlen, right - left + 1);
if (minlen == 1) return 1; // Return early if possible.
sum -= nums[left];
}
}
}
return minlen == (N + 1) ? 0 : minlen;
}
};
__________________________________________________________________________________________________
sample 9752 kb submission
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int minLen = INT_MAX;
for (int i = 0; i < nums.size(); i++) {
int residual = s;
int curLen = 0;
for (int j = i; j < nums.size(); j++) {
residual -= nums[j];
curLen += 1;
if (residual <= 0) {
minLen = min(minLen, curLen);
break;
}
}
}
if (minLen == INT_MAX)
return 0;
return minLen;
}
};
__________________________________________________________________________________________________