This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package 第03期.mca_05;
import java.util.Arrays;
// 给定一个正数数组arr,代表若干人的体重
// 再给定一个正数limit,表示所有船共同拥有的载重量
// 每艘船最多坐两人,且不能超过载重
// 想让所有的人同时过河,并且用最好的分配方法让船尽量少
// 返回最少的船数
// 测试链接 : https://leetcode.cn/problems/boats-to-save-people/
public class Code01_BoatsToSavePeople {
// 首尾双指针的解法
public static int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int ans = 0;
int l = 0;
int r = people.length - 1;
int sum = 0;
while (l <= r) {
sum = l == r ? people[l] : people[l] + people[r];
if (sum > limit) {
r--;
} else {
l++;
}
ans++;
return ans;