救生艇
对撞双指针(有贪心那味了)
代码
class Solution {
//对撞双指针
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int n = people.length;
int leavePeople = 0;//被接走的人数
int res = 0;
int l = 0,r = n-1;
while(l < r){
int sumTwo = people[l]+people[r];
if(sumTwo > limit){//r位置的人被单独接走
r--;
leavePeople++;
}else{///l、r位置的人被接走
l++;
r--;
leavePeople+=2;
}
res++;
}
//最后只有两种情况
//1、留下一人需要单独接走(结果+1)
//2、最后刚好接完了
return leavePeople == n ? res : res + 1;
}
}
不一样的烟火