0
点赞
收藏
分享

微信扫一扫

救生艇

悲催博士僧 2021-09-21 阅读 45
今日算法
题目描述:
示例 1:
示例 2:
示例 3:
题目分析:
  1. 每个人都坐上船,需要的最小船数
    • 每条船最多可以载两人
    • 每条船的人体重之和小于等于limit
思路:
代码实现:
class Solution {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people);
        int result = 0;
        int left = 0, right = people.length - 1;
        while (left < right) {
            if (people[left] + people[right] > limit) {
                right--;
                result++;
            } else if (people[left] + people[right] <= limit) {
                left++;
                right--;
                result++;
            }
            if (left == right && people[left] <= limit) result++;
        }
        return result;
    }
}
举报

相关推荐

0 条评论