zoukankan      html  css  js  c++  java
  • LeetCode 881 救生艇

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

    **贪心算法 **

    /**
     * 双指针+ 排序
     *
     * @param people
     * @param limit
     * @return
     */
    public static int numRescueBoats(int[] people, int limit) {
        if (people == null || people.length == 0) return 0;
    
        Arrays.sort(people);
    
        int left = 0;
        int rigth = people.length - 1;
        int num = 0;
        while (left <= rigth) {
            if (people[rigth] > limit) return 0;
            if ( left < rigth && people[rigth] + people[left] <= limit) {
                left++;
            }
            num++;
            rigth--;
        }
        return num;
    }
    

    测试用例

    public static void main(String[] args) {
        int[] people = new int[]{1, 2};
        int limit = 3;
        int num = NumRescueBoats.numRescueBoats(people, limit);
        System.out.println("NumRescueBoats demo01 result : " + num);
    
        people = new int[]{3, 2, 2, 1};
        limit = 3;
        num = NumRescueBoats.numRescueBoats(people, limit);
        System.out.println("NumRescueBoats demo02 result : " + num);
    
        people = new int[]{3, 5, 3, 4};
        limit = 5;
        num = NumRescueBoats.numRescueBoats(people, limit);
        System.out.println("NumRescueBoats demo03 result : " + num);
    }
    
  • 相关阅读:
    spring的好处
    2.3 java中类路径
    java的编译器为什么会自动编译java文件
    oracle添加字段或者删除字段-转载
    sql 取新的列名含义
    window.onload =writeMessage(); 与window.onload =writeMessage;的区别
    HTML DOM 之<textare>标签
    最新学习网址大全
    C#读写txt文件的两种方法介绍
    固定分隔符字符串与数组互转及ArrayList与数组(Array)互转
  • 原文地址:https://www.cnblogs.com/fyusac/p/15191401.html
Copyright © 2011-2022 走看看