# # Leetcode 第29场双周赛题解

## # Problem A - 去掉最低工资和最高工资后的工资平均值 (opens new window)

class Solution:
def average(self, salary: List[int]) -> float:
return (sum(salary) - min(salary) - max(salary)) / (len(salary) - 2)

1
2
3

## # Problem B - n 的第 k 个因子 (opens new window)

$O(\sqrt{n})$求出$n$的所有因子，排序后取第$k$个即可。

class Solution {
public:
int kthFactor(int n, int k) {
set<int> s;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
s.insert(i);
s.insert(n / i);
}
}
vector<int> v(s.begin(), s.end());
if (k > v.size())
return -1;
return v[k - 1];
}
};

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

## # Problem C - 删掉一个元素以后全为 1 的最长子数组 (opens new window)

class Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size();
vector<int> left(n), right(n);
for (int i = 1; i < n; ++i) {
if (nums[i - 1] == 1)
left[i] = left[i - 1] + 1;
}
for (int i = n - 2; i >= 0; --i) {
if (nums[i + 1] == 1)
right[i] = right[i + 1] + 1;
}
int ans = 0;
for (int i = 0; i < n; ++i)
ans = max(ans, left[i] + right[i]);
return ans;
}
};

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

## # Problem D - 并行课程 II (opens new window)

for (int i = 1; i < (1 << n); ++i) {
for (int j = i; j; j = (j - 1) & i) {
// ...
}
}

1
2
3
4
5

const int INF = 0x3f3f3f3f;
int dp[40000];
bool valid[40000];

class Solution {
public:
int minNumberOfSemesters(int n, vector<vector<int>>& dependencies, int k) {
vector<int> pre(n), in(n);
for (auto v : dependencies) {
in[v[1] - 1]++;
}
queue<int> q;
for (int i = 0; i < n; ++i)
if (in[i] == 0)
q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
pre[v] |= pre[u] | (1 << u);
in[v]--;
if (in[v] == 0)
q.push(v);
}
}

memset(valid, true, sizeof(valid));
for (int i = 1; i < (1 << n); ++i) {
vector<int> t;
for (int j = 0; j < n; ++j)
if (i & (1 << j))
t.emplace_back(j);
if (t.size() > k) {
valid[i] = false;
continue;
}
for (int j : t) {
for (int p : t)
if (pre[j] & (1 << p)) {
valid[i] = false;
break;
}
if (!valid[i])
break;
}
}

memset(dp, 0x3f, sizeof(dp));
dp[0] = 0;
for (int i = 1; i < (1 << n); ++i) {
for (int j = i; j; j = (j - 1) & i)
if (valid[j] && dp[i - j] != INF)
dp[i] = min(dp[i], dp[i - j] + 1);
}
return dp[(1 << n) - 1];
}
};

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