Skip to content

Commit ffdd75f

Browse files
committed
Create 881._Boats_to_Save_People.md
1 parent 77c36cb commit ffdd75f

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# 881. Boats to Save People
2+
3+
**<font color=red>难度: Medium</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/boats-to-save-people/description/
10+
11+
> 内容描述
12+
13+
```
14+
The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
15+
16+
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
17+
18+
Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)
19+
20+
21+
22+
Example 1:
23+
24+
Input: people = [1,2], limit = 3
25+
Output: 1
26+
Explanation: 1 boat (1, 2)
27+
Example 2:
28+
29+
Input: people = [3,2,2,1], limit = 3
30+
Output: 3
31+
Explanation: 3 boats (1, 2), (2) and (3)
32+
Example 3:
33+
34+
Input: people = [3,5,3,4], limit = 5
35+
Output: 4
36+
Explanation: 4 boats (3), (3), (4), (5)
37+
Note:
38+
39+
1 <= people.length <= 50000
40+
1 <= people[i] <= limit <= 30000
41+
42+
```
43+
44+
## 解题方案
45+
46+
> 思路 1
47+
******- 时间复杂度: O(1)******- 空间复杂度: O(N)******
48+
49+
* 使用贪心算法,将数组进行排序之后进行处理
50+
51+
代码:
52+
53+
```javascript
54+
/**
55+
* @param {number[]} people
56+
* @param {number} limit
57+
* @return {number}
58+
*/
59+
var numRescueBoats = function(people, limit) {
60+
people.sort(function (a,b) { return a-b });
61+
var num=0;
62+
for(var left = 0,right = people.length-1;right-left>=0;right--){
63+
if(people[left]+people[right]<=limit)
64+
left++;
65+
num++;
66+
}
67+
return num;
68+
};
69+
```
70+

0 commit comments

Comments
 (0)