209. 长度最小的子数组
为保证权益,题目请参考 209. 长度最小的子数组(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution {
public:
int minSubArrayLen(int s, vector<int> &nums) {
if (nums.size() == 0) {
return 0;
}
int l = 0;
int r = 0;
int minLength = INT_MAX;
int curValue = nums[0];
while (r + 1 < nums.size()) {
while (curValue < s && r + 1 < nums.size()) {
r++;
curValue += nums[r];
}
while (curValue - nums[l] >= s) {
curValue -= nums[l];
l++;
}
if (curValue >= s) {
minLength = min(minLength, r - l + 1);
curValue -= nums[l];
l++;
}
}
return minLength == INT_MAX ? 0 : minLength;
}
};
int main() {
vector<int> nums;
nums.push_back(2);
nums.push_back(3);
nums.push_back(1);
nums.push_back(2);
nums.push_back(4);
nums.push_back(3);
Solution so;
cout << so.minSubArrayLen(7, nums) << endl;
return 0;
}
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
52
53
54
55
56
57
58
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
52
53
54
55
56
57
58