# # Leetcode 第269场周赛题解

## # Problem A - 找出数组排序后的目标下标 (opens new window)

### # 方法一：暴力

• 时间复杂度$\mathcal{O}(N\log N)$
• 空间复杂度$\mathcal{O}(N)$

class Solution:
def targetIndices(self, nums: List[int], target: int) -> List[int]:
return [i for i, num in enumerate(sorted(nums)) if num == target]

1
2
3

## # Problem B - 半径为 k 的子数组平均值 (opens new window)

### # 方法一：模拟

• 时间复杂度$\mathcal{O}(N)$
• 空间复杂度$\mathcal{O}(N)$

class Solution:
def getAverages(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
s = 0
ans = [-1] * n
for i in range(n):
s += nums[i]
if i >= 2 * k:
ans[i - k] = s // (2 * k + 1)
s -= nums[i - k * 2]
return ans

1
2
3
4
5
6
7
8
9
10
11

## # Problem C - 从数组中移除最大值和最小值 (opens new window)

### # 方法一：贪心

• 只取左边
• 只取右边
• 取两边

• 时间复杂度$\mathcal{O}(N)$
• 空间复杂度$\mathcal{O}(1)$

class Solution:
def minimumDeletions(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return 1
l = nums.index(min(nums))
r = nums.index(max(nums))
if l > r:
l, r = r, l
return min(n - (r - l - 1), r + 1, n - l)

1
2
3
4
5
6
7
8
9
10

## # Problem D - 找出知晓秘密的所有专家 (opens new window)

### # 方法一：多源BFS

• 时间复杂度$\mathcal{O}(N+E+MAXT)$
• 空间复杂度$\mathcal{O}(N+E)$

class Solution {
public:
vector<int> findAllPeople(int n, vector<vector<int>>& meetings, int firstPerson) {
vector<bool> known(n);
known[0] = true;
known[firstPerson] = true;

int maxT = 0;
for (auto &meeting : meetings)
maxT = max(maxT, meeting[2]);
vector<vector<pair<int, int>>> time(maxT + 1);
for (auto &meeting : meetings)
time[meeting[2]].emplace_back(meeting[0], meeting[1]);

for (int i = 1; i <= maxT; ++i) {
if (time[i].empty())
continue;

unordered_set<int> vis; // 用集合，而不是布尔数组
queue<int> q;
for (auto &[u, v] : time[i]) { // 设置邻接表
if (known[u] && !vis.count(u)) {
vis.insert(u);
q.push(u);
}
if (known[v] && !vis.count(v)) {
vis.insert(v);
q.push(v);
}
}

while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (!vis.count(v)) {
known[v] = true;
vis.insert(v);
q.push(v);
}
}
}

for (auto &[u, v] : time[i]) { // 还原邻接表
}
}

vector<int> ans;
for (int i = 0; i < n; ++i)
if (known[i])
ans.push_back(i);
return ans;
}
};

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
59