- 分析
贪心题,先排序,然后双指针遍历,从后面开始选择,选择完后看剩下的空间是否可以承载剩余的体重最小的人。 - 代码
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
int size = people.size();
sort(people.begin(), people.end());
int ans = 0;
int left =0;
int right = size-1;
while(left<=right){
int temp = limit - people[right];
if(temp >=people[left]) left++;
ans++;
right--;
}
return ans;
}
};