Skip to content

Commit 37c3395

Browse files
committed
add solution of problem 0881.
1 parent 6f33308 commit 37c3395

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
## 救生艇
2+
3+
### 问题描述
4+
5+
`i` 个人的体重为 `people[i]`,每艘船可以承载的最大重量为 `limit`
6+
7+
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 `limit`
8+
9+
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
10+
11+
**示例1:**
12+
```
13+
输入:people = [1,2], limit = 3
14+
输出:1
15+
解释:1 艘船载 (1, 2)
16+
```
17+
**示例2:**
18+
```
19+
输入:people = [3,2,2,1], limit = 3
20+
输出:3
21+
解释:3 艘船分别载 (1, 2), (2) 和 (3)
22+
```
23+
**示例3:**
24+
```
25+
输入:people = [3,5,3,4], limit = 5
26+
输出:4
27+
解释:4 艘船分别载 (3), (3), (4), (5)
28+
```
29+
**提示:**
30+
- 1 <= people.length <= 50000
31+
- 1 <= people[i] <= limit <= 30000
32+
33+
### 解法
34+
最重的人必定和最轻的人一组。如果最重的人加最轻的人的体重都超标了,则最重的人只能单独一组。使用头尾双指针即可解决问题。
35+
36+
```python
37+
class Solution:
38+
def numRescueBoats(self, people, limit):
39+
people.sort()
40+
left = 0
41+
right = len(people) - 1
42+
ans = 0
43+
while left < right:
44+
if people[left] + people[right] <= limit:
45+
ans += 1
46+
left += 1
47+
right -= 1
48+
else:
49+
ans += 1
50+
right -= 1
51+
else:
52+
if left == right:
53+
ans += 1
54+
return ans
55+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def numRescueBoats(self, people, limit):
3+
"""
4+
:type people: List[int]
5+
:type limit: int
6+
:rtype: int
7+
"""
8+
people.sort()
9+
left = 0
10+
right = len(people) - 1
11+
ans = 0
12+
while left < right:
13+
if people[left] + people[right] <= limit:
14+
ans += 1
15+
left += 1
16+
right -= 1
17+
else:
18+
ans += 1
19+
right -= 1
20+
else:
21+
if left == right:
22+
ans += 1
23+
return ans

0 commit comments

Comments
 (0)