LeetCode 881 救生艇

  • 分析
    贪心题,先排序,然后双指针遍历,从后面开始选择,选择完后看剩下的空间是否可以承载剩余的体重最小的人。
  • 代码
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;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaoan08133192/article/details/119937217