881. 救生艇
思路:将数组people升序排序,然后使用双指针。采用贪心的策略,最大的搭配最小的看看能不能<=limit,不能的话,那么最大的单独一艘船。
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
int n=people.size();
sort(people.begin(),people.end());
int l=0,r=n-1;
int ans=0;
while(l<=r){
if(people[l]+people[r]>limit){
ans++;
r--;
}else{
ans++;
l++;
r--;
}
}
return ans;
}
};