LeetCode 881. 救生艇

56 阅读1分钟

题目

给定数组 people 。people[i]表示第 i 个人的体重 ,船的数量不限,每艘船可以承载的最大重量为 limit

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

返回 承载所有人所需的最小船数 。

思路

暴力解法.

升序排序后, 如果右边的值等于limit 或者 右边的值加左边的值 > limit 则只可以装下一个人,

如果 < limit 则可以装下最大和最小的这两个人

代码

class Solution {
    public int numRescueBoats(int[] people, int limit) {
        //升序排序
        Arrays.sort(people);
        int n = people.length;
        int ans = 0;
        int left = 0;
        int right = n - 1;
        while (left <= right) {
            if (left != right) {
                if (people[right] != limit && people[right] + people[left] <= limit) {
                    left++;
                }
                right--;
            } else {
                ans++;
                break;
            }
            ans++;
        }
        return ans;
    }
}

题解

leetcode.cn/problems/bo…