博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 881. Boats to Save People
阅读量:4621 次
发布时间:2019-06-09

本文共 1748 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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 = 3Output: 1Explanation: 1 boat (1, 2)

Example 2:

Input: people = [3,2,2,1], limit = 3Output: 3Explanation: 3 boats (1, 2), (2) and (3)

Example 3:

Input: people = [3,5,3,4], limit = 5Output: 4Explanation: 4 boats (3), (3), (4), (5)

Note:

  • 1 <= people.length <= 50000
  • 1 <= people[i] <= limit <= 30000

题解:

When trying to find out minimum num ber of boats to carry every given person, it is best to sort array first and let heaviest person and lightest person fit the boat first.

If it is overweight, then only let the heaviest person take and boat, res++.

Otherwise, let both of them take the boat, and since boat could carry at most 2 people at the same time, move both pointers, res++.

Time Complexity: O(nlogn). n = people.length.

Space: O(1).

AC Java: 

1 class Solution { 2     public int numRescueBoats(int[] people, int limit) { 3         if(people == null || people.length == 0){ 4             return 0; 5         } 6          7         Arrays.sort(people); 8         int res = 0; 9         int i = 0; 10         int j = people.length-1;11         while(i<=j){12             if(people[i]+people[j]<=limit){13                 i++;14                 j--;15             }else{16                 j--;17             }18             19             res++;20         }21         22         return res;23     }24 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11421611.html

你可能感兴趣的文章
create-react-app 配置sass
查看>>
02_关系数据库
查看>>
在win7电脑中如何查看运行进程的PID标识符
查看>>
[Vue] vue-cli3.0安装
查看>>
C++学习之字符串
查看>>
图像化列表
查看>>
2014年10月9日——语言基础2
查看>>
mysql查
查看>>
[正则表达式]难点和误区
查看>>
217. Contains Duplicate
查看>>
hadoop遇到问题总结
查看>>
Windows下手动安装redis服务
查看>>
把 MongoDB 当成是纯内存数据库来使用(Redis 风格)
查看>>
PyTorch 1.0 中文官方教程:使用ONNX将模型从PyTorch传输到Caffe2和移动端
查看>>
LeetCode 4Sum
查看>>
BBC-The Race and a quiz
查看>>
大端小端
查看>>
IntelliJ IDEA 把java项目导出成可执行的jar
查看>>
DynamicReports
查看>>
鼠标经过图像改变实现
查看>>