[leetcode]881. Boats to Save People

[leetcode]881. Boats to Save People


Analysis

出太阳啦~—— [每天刷题并不难0.0]

The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)
在这里插入图片描述

Explanation:

按照体重从大到小的顺序给people排序,然后每次尽量让体重最大和体重最小的人一起坐船,如果超过上限的话,就让体重最大的单独坐船。

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/86470208