[LeetCode] 881. Boats to Save People
Posted CNoodle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 881. Boats to Save People相关的知识,希望对你有一定的参考价值。
The i
-th person has weight people[i]
, and each boat can carry a maximum weight of limit
.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit
.
Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Note:
1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000
救生艇。
第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/boats-to-save-people
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是贪心 + two pointer。这里贪心贪的是一条船能否在已经装了一个很重的人的情况下还能再装一个比较轻的人。思路是首先对input排序,因为重量最大的人也一定能被一艘船装下,所以当我们把重量最大的那个人放进一艘船的时候,我们试图去找的是看看这条船是否能再装下一个重量较轻的人。这个重量较轻的人可以从重量最轻的人开始看,如此这个策略才是最优的。
时间O(nlogn) - 对数组排序
空间O(1)
Java实现
1 class Solution { 2 public int numRescueBoats(int[] people, int limit) { 3 Arrays.sort(people); 4 int i = 0; 5 int j = people.length - 1; 6 int res = 0; 7 while (i <= j) { 8 res++; 9 if (people[i] + people[j] <= limit) { 10 i++; 11 } 12 j--; 13 } 14 return res; 15 } 16 }
以上是关于[LeetCode] 881. Boats to Save People的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 881. Boats to Save People
[LeetCode] Boats to Save People 渡人的船