第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
示例 1:
输入:people = [1,2], limit = 3
输出:1
解释:1 艘船载 (1, 2)
示例 2:
输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
示例 3:
输入:people = [3,5,3,4], limit = 5
输出:4
解释:4 艘船分别载 (3), (3), (4), (5)
提示:
1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000
方法一(排序+双指针)、
将所有人按体重排序,第一个人和最后一个人为超载则可以坐一条船,否则最后一个人单独一条船
/**
* 排序加双指针
*
* @param people people
* @param limit limit
* @return int
*/
public int numRescueBoats(int[] people, int limit) {
//数组排序
Arrays.sort(people);
int left = 0;
int right = people.length - 1;
int result = 0;
while (left <= right) {
//判断左节点和右节点的和是否大于最大重量
//如果大于则说明右节点需要一张单独的船
//如果小于或等于说明当节前左节点和右点可以同一条船
if (people[left] + people[right] <= limit) {
left++;
}
right--;
result++;
}
return result;
}
方法二、
记录每种体重下一共有多少人,然后按体重分船
/**
* 通过创建重量类型数据,计算每种类型下有多少人
* @param people people
* @param limit limit
* @return int
*/
public int numRescueBoats(int[] people, int limit) {
//统计每类重量下的人有多少(从重量为0开始,最大重量不会超过限制,所以数组长度为 limit+1 就行)
int[] weightCount = new int[limit + 1];
for (int peopleWeight : people) {
weightCount[peopleWeight]++;
}
int left = 0;
int right = weightCount.length - 1;
int result = 0;
while (left < right) {
//获取左边类型数量不为0的重量
while (weightCount[left] == 0) {
left++;
if(left > right){
break;
}
}
//获取右边类型数量不为0的重量
while (weightCount[right] == 0) {
right--;
if(left > right){
break;
}
}
//当前左边重量类型大于右边重量类型则结束循环
if(left >= right){
break;
}
//判断当前重量和是否小于等于限制
//1 如果小于等于限制,则这两类重量的人可以一条船,所以哪类重量的人数少就需要多少条船,
// 并把人数少的重量类型的数量赋值为0(已经分到船的人需要移除)
//2 如果大于限制,则较大重量类型下的所以人都需要一条船,
// 所需船数量加上较大重量类型的数量,并把该重量类型的数量赋值为0
if (left + right <= limit) {
if (weightCount[left] > weightCount[right]) {
result += weightCount[right];
weightCount[left] -= weightCount[right];
weightCount[right]=0;
right--;
} else if (weightCount[left] < weightCount[right]) {
result += weightCount[left];
weightCount[right] -= weightCount[left];
weightCount[left]=0;
left++;
} else {
result += weightCount[left];
weightCount[left]=0;
weightCount[right]=0;
left++;
right--;
}
} else {
result += weightCount[right];
weightCount[right]=0;
right--;
}
}
//如果遍历到同一种重量类型,则存在两种情况
//1 该重量类型可以两人一条船
//2 该重量类型不可以两人一条船
if (left == right) {
if (left + right > limit) {
result += weightCount[left];
} else {
result += (weightCount[left] % 2 == 0 ? (weightCount[left] / 2) : (weightCount[left] / 2) + 1);
}
}
return result;
}
转载于:https://www.ycblog.top/article?articleId=153&commentPageNum=1