1248. 统计「优美子数组」
为保证权益,题目请参考 1248. 统计「优美子数组」(From LeetCode).
解决方案1
CPP
C++
/*
* 1248
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int numberOfSubarrays(vector<int> &nums, int k) {
int ans = 0;
vector<int> dp;
dp.push_back(-1);
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] % 2 == 1) {
dp.push_back(i);
}
}
dp.push_back(nums.size());
for (int i = 1; i + (k - 1) < dp.size() - 1; ++i) {
ans += (dp[i] - dp[i - 1]) * (dp[i + k] - dp[i + k - 1]);
}
return ans;
}
};
int main() {
vector<int> vec;
vec.push_back(2);
vec.push_back(2);
vec.push_back(2);
vec.push_back(1);
vec.push_back(2);
vec.push_back(2);
vec.push_back(1);
vec.push_back(2);
vec.push_back(2);
vec.push_back(2);
Solution so;
cout << so.numberOfSubarrays(vec, 2) << 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
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