# # Leetcode 第31场双周赛题解

## # Problem A - 在区间范围内统计奇数数目 (opens new window)

class Solution {
public:
int countOdds(int low, int high) {
int delta = high - low + 1;
return delta / 2 + (delta % 2 == 0 ? 0 : low % 2);
}
};

1
2
3
4
5
6
7

## # Problem B - 和为奇数的子数组数目 (opens new window)

const int MOD = 1e9 + 7;

class Solution {
public:
int numOfSubarrays(vector<int>& arr) {
int n = arr.size();
int ans = 0;
int odd = 0, even = 1, sum = 0;
for (int i : arr) {
sum += i;
if (sum % 2 == 0) {
ans = (ans + odd) % MOD;
even++;
}
else {
ans = (ans + even) % MOD;
odd++;
}
}
return ans;
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

## # Problem C - 字符串的好分割数目 (opens new window)

class Solution {
public:
int numSplits(string s) {
int ans = 0;
map<char, int> l, r;
for (char c : s)
r[c]++;
for (char c : s) {
r[c]--;
if (r[c] == 0)
r.erase(c);
l[c]++;
if (r.size() == l.size())
ans++;
}
return ans;
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

## # Problem D - 形成目标数组的子数组最少增加次数 (opens new window)

class Solution {
public:
int minNumberOperations(vector<int>& target) {
int ans = 0, last = 0;
for (int i : target) {
if (i > last)
ans += i - last;
last = i;
}
return ans;
}
};

1
2
3
4
5
6
7
8
9
10
11
12