Skip to content

Commit 4cce8e7

Browse files
committed
2025-07-13
1 parent a433ec1 commit 4cce8e7

3 files changed

Lines changed: 68 additions & 3 deletions

File tree

algorithm/动态规划/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
## 3. 常见类型
2323

2424
1. **背包DP**
25-
- 01背包
25+
- [01背包](/algorithm/动态规划/背包问题/01背包.md)
2626
- 完全背包
2727
- 多重背包等
2828

algorithm/动态规划/背包问题/01背包.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ $$
3333

3434
## 5. 代码
3535

36-
- 时间复杂度$O(n \times C)$
37-
- 空间复杂度$O(n \times C)$
36+
- 时间复杂度: $O(n \times C)$
37+
- 空间复杂度: $O(n \times C)$
3838

3939
**Python3**
4040

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# [2410. 运动员和训练师的最大匹配数](https://leetcode.cn/problems/maximum-matching-of-players-with-trainers/description/)
2+
3+
> **日期**:2025-07-13
4+
> **所用时间**:5min
5+
6+
## 1. 贪心
7+
8+
### 题目描述
9+
10+
有一组运动员和一组训练师,每个运动员有一个能力值,每个训练师有一个训练能力。若某个运动员的能力值小于等于某个训练师的训练能力,则该运动员可以和该训练师匹配。每个运动员和训练师最多只能匹配一次。问最多能匹配多少对。
11+
12+
### 解题思路
13+
14+
本题是典型的**贪心**匹配问题。我们希望让尽可能多的运动员被匹配上。具体做法如下:
15+
16+
1. **排序**:先将`players``trainers`数组从小到大排序。
17+
2. **双指针**:用两个指针`i``j`分别指向当前未匹配的运动员和训练师。
18+
3. **遍历匹配**
19+
- 如果当前运动员`players[i]`的能力值小于等于当前训练师`trainers[j]`的训练能力,则匹配成功,两个指针都后移,匹配数加一。
20+
- 否则,说明当前训练师无法匹配当前运动员,需要让训练师指针后移,寻找能力更强的训练师。
21+
4. **终止条件**:只要有一方遍历完就结束。
22+
23+
这种贪心策略保证了每个运动员都尽量用能力最接近的训练师去匹配,从而最大化匹配数。
24+
25+
#### 例子
26+
27+
- `players = [4,7,9]`
28+
- `trainers = [8,2,5,8]`
29+
30+
排序后:
31+
- `players = [4,7,9]`
32+
- `trainers = [2,5,8,8]`
33+
34+
匹配过程:
35+
- 4 vs 2(不行),训练师后移
36+
- 4 vs 5(可以),匹配,i=1, j=2, ans=1
37+
- 7 vs 8(可以),匹配,i=2, j=3, ans=2
38+
- 9 vs 8(不行),训练师后移
39+
- 9 vs 8(不行),训练师后移,结束
40+
41+
最终答案为2。
42+
43+
### 复杂度分析
44+
45+
- 时间复杂度:排序$O(n\log n + m\log m)$,遍历$O(n+m)$,总共$O(n\log n + m\log m)$。
46+
- 空间复杂度:$O(1)$(原地排序)。
47+
48+
**Python3**
49+
50+
```python
51+
class Solution:
52+
def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:
53+
players.sort()
54+
trainers.sort()
55+
56+
ans = i = j = 0
57+
while i < len(players) and j < len(trainers):
58+
if players[i] <= trainers[j]:
59+
i += 1
60+
j += 1
61+
ans += 1
62+
else:
63+
j += 1
64+
return ans
65+
```

0 commit comments

Comments
 (0)