第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
输入:people = [1,2], limit = 3
输出:1
解释:1 艘船载 (1, 2)
输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
解题
如果最重的人无法与最轻的人配对,那么只能独自乘船。所此时先排序完,按选择最大和最小的进行匹配
public int numRescueBoats(int[] people, int limit) {
//假如
if (people.length<=0) return 0;
Arrays.sort(people);//按照体重大排序
int count=0;//记录
int left=0,right=people.length-1;
while (left<right){
if (left==right) {
count++;
break;}
if (limit-people[right]-people[left]>=0){
right--;
left++;
count++;
}else {
right--;
count++;
}
}
return count;
}
一开始是这样,后面选择了优化了代码
public int numRescueBoats(int[] people, int limit) {
//假如
if (people.length<=0) return 0;
Arrays.sort(people);//按照体重大排序
int count=0;//记录
int left=0,right=people.length-1;
while (left<=right){
if (people[right]+people[left]<=limit){
left++;
}
right--;
count++;
}
return count;
}