zoukankan      html  css  js  c++  java
  • 0881. Boats to Save People (M)

    Boats to Save People (M)

    题目

    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.)

    Example 1:

    Input: people = [1,2], limit = 3
    Output: 1
    Explanation: 1 boat (1, 2)
    

    Example 2:

    Input: people = [3,2,2,1], limit = 3
    Output: 3
    Explanation: 3 boats (1, 2), (2) and (3)
    

    Example 3:

    Input: people = [3,5,3,4], limit = 5
    Output: 4
    Explanation: 4 boats (3), (3), (4), (5)
    

    Note:

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

    题目

    规定一艘船最多可以载两人,且有限定载重量。给定n个人的重量,判断最少需要几艘船能运送所有人。

    思路

    贪心 + Two Pointers。先对数组排序,每次一定会安排一个最重的一人上船,这时判断还未上船的最轻的人能否也挤上去。重复直到所有人都上船。


    代码实现

    Java

    class Solution {
        public int numRescueBoats(int[] people, int limit) {
            int count = 0;
            Arrays.sort(people);
            int left = 0, right = people.length - 1;
            while (left <= right) {
                if (people[left] + people[right] <= limit) {
                    left++;
                }
                right--;
                count++;
            }
            return count;
        }
    }
    
  • 相关阅读:
    查找表类算法//字母异位词分组
    查找表类算法//四数相加 II
    查找表类算法//四数相加 II
    第六章 类文件结构
    第六章 类文件结构
    查找表的算法//四数之和
    查找表的算法//四数之和
    第五章 调优案例分析与实战
    第五章 调优案例分析与实战
    C++_基础4-分支语句和逻辑运算符
  • 原文地址:https://www.cnblogs.com/mapoos/p/14273944.html
Copyright © 2011-2022 走看看