第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/boats-to-save-people
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:先把数组进行排序,然后使用对撞双指针。
Java:
执行用时:18 ms, 在所有 Java 提交中击败了64.18%的用户
内存消耗:47.5 MB, 在所有 Java 提交中击败了12.65%的用户
class Solution {
public int numRescueBoats(int[] people, int limit) {
if(people==null||people.length==0)
{
return 0;
}
int num=0;
Arrays.sort(people);
int i=0;
int j=people.length-1;
while(i<=j)
{
if(people[i]+people[j]<=limit)
{
i+=1;
}
j-=1;
num++;
}
if(i==j)
{
num+=1;
}
return num;
}
}
Python:
执行用时:136 ms, 在所有 Python3 提交中击败了47.35%的用户
内存消耗:19.9 MB, 在所有 Python3 提交中击败了78.56%的用户
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
if len(people)==0 or people==None:
return 0
num=0
i=0
j=len(people)-1
people.sort()
while i<=j:
if people[i]+people[j]<=limit:
i+=1
j-=1
num+=1
return num