救生艇
思路
每个船只能乘坐两个人,不是乘坐多个人,这道题就是贪心算法。
体重较大的人,如果连此时剩余人群中体重最小的人都装不下,那么就需要单独给他一搜船,使用双指针算法解决该问题
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int res = 0;
int l = 0, n = people.size(), h = n - 1;
while (l <= h)
{
if (people[l] + people[h] > limit){
h -- ;
}
else
l ++ , h -- ;
res ++ ;
}
return res;
}
};