[LeetCode]881. 救生艇

最大和最小一条船,贪心策略

Posted by JinFei on August 30, 2021

题目描述

第i个人的体重为 people[i],每艘船可以承载的最大重量为limit。 每艘船最多可同时载两人,但条件是这些人的重量之和最多为limit。 返回载到每一个人所需的最小船数。(保证每个人都能被船载)。

Example 1:

输入:people = [1,2], limit = 3 输出:1 解释:1 艘船载 (1, 2)

Example 2:

输入:people = [3,2,2,1], limit = 3 输出:3 解释:3 艘船分别载 (1, 2), (2) 和 (3)

Example 3:

输入:people = [3,5,3,4], limit = 5 输出:4 解释:4 艘船分别载 (3), (3), (4), (5)

Constraints:

  • 1 <= people.length <= 50000
  • 1 <= people[i] <= limit <= 30000

解题思路

  • 贪心思路,先排序(其实质思想是 最大化看能不能同乘一条船)
  • 双指针思想,前后分别指向当前最轻的和最重的
  • 如果最重的和最轻的大于限制了,那么最重的不能和任意一个人同乘一条船(需要单独坐一条船)
  • 如果小于限制了,那么可以同乘一条船

C++代码

class Solution {
public:
    int numRescueBoats(vector<int>& people, int limit) {
        sort(people.begin(), people.end());
        int ans = 0;
        int begin = 0;
        int end = people.size() - 1;
        while(begin <= end){
            if(people[begin] + people[end] > limit){
                end--;
            }else{
                begin++;
                end--;
            }
            ans++;
        }
        return ans;
    }
};