# # Leetcode 第202场周赛题解

## # Problem A - 存在连续三个奇数的数组 (opens new window)

class Solution {
public:
bool threeConsecutiveOdds(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i + 2 < n; ++i)
if ((arr[i] & 1) && (arr[i + 1] & 1) && (arr[i + 2] & 1))
return true;
return false;
}
};

1
2
3
4
5
6
7
8
9
10

## # Problem B - 使数组中所有元素相等的最小操作数 (opens new window)

f(n)=\left\{ \begin{aligned} & n^2/4 & n\text{为偶数} \\ & (n+1)(n-1)/4 & n\text{为奇数} \end{aligned} \right.

class Solution {
public:
int minOperations(int n) {
return n % 2 == 0 ? n * n / 4 : (n + 1) * (n - 1) / 4;
}
};

1
2
3
4
5
6

## # Problem C - 两球之间的磁力 (opens new window)

class Solution {
public:
int maxDistance(vector<int>& position, int m) {
int n = position.size();
sort(position.begin(), position.end());
m -= 2;
int l = 1, r = position[n - 1] - position[0];
while (l <= r) {
int mid = (l + r) / 2;
int left = 0, cnt = 0;
for (int i = 1; i < n - 1; ++i) {
if (position[n - 1] - position[i] < mid)
break;
if (position[i] - position[left] >= mid)
left = i, cnt++;
}
if (cnt >= m)
l = mid + 1;
else
r = mid - 1;
}
return r;
}
};

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

## # Problem D - 吃掉 N 个橘子的最少天数 (opens new window)

class Solution {
public:
int minDays(int n) {
unordered_set<int> s;
queue<pair<int, int>> q;
q.push({n, 0});
s.insert(n);
while (!q.empty()) {
auto [x, d] = q.front();
q.pop();
if (x == 0)
return d;
if (x % 2 == 0 && !s.count(x / 2))
q.push({x / 2, d + 1}), s.insert(x / 2);
if (x % 3 == 0 && !s.count(x / 3))
q.push({x / 3, d + 1}), s.insert(x / 3);
if (!s.count(x - 1))
q.push({x - 1, d + 1}), s.insert(x - 1);
}
return 0;
}
};

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