LeetCode 881. 救生艇(C++、python)

第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit

每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit

返回载到每一个人所需的最小船数。(保证每个人都能被船载)。

示例 1:

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

示例 2:

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

示例 3:

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

提示:

1 <= people.length <= 50000

1 <= people[i] <= limit <= 30000

C++

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

python

class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        n=len(people)
        people.sort()
        res=0
        left=0
        right=n-1
        while left<=right:
            if people[left]+people[right]<=limit:
                res+=1
                left+=1
                right-=1
            else:
                res+=1
                right-=1
        return res
                
        

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/88040598