图解LeetCode——1710. 卡车上的最大单元数(难度:简单)

一、题目

请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi] :

  • numberOfBoxesi 是类型 i 的箱子的数量。
  • numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。

整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 返回卡车可以装载 单元 的 最大 总数。

二、示例

2.1> 示例 1:

【输入】boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
【输出】8
【解释】箱子的情况如下:1 个第一类的箱子,里面含 3 个单元。2 个第二类的箱子,每个里面含 2 个单元。3 个第三类的箱子,每个里面含 1 个单元。可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8

2.2> 示例 2:

【输入】boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
【输出】91

提示:

  • 1 <= boxTypes.length <= 1000
  • 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
  • 1 <= truckSize <= 10^6

三、解题思路

根据题目要求,要获得卡车可以装载单元的最大总数。那么我们是需要执行下面两个步骤即可:

步骤1】根据numberOfUnitsPerBox对数组boxTypes进行排序。
步骤2】从大到小获取boxType,并计算总装载单元数,直到满足truckSize

其中,关于排序,我们可以采用Arrays.sort(...)方法对数组boxTypes进行排序;并且由于提示中描述了numberOfUnitsPerBox <= 1000,所以我们也可以通过创建int[1001]的数组来实现排序。具体操作如下图所示:

时间复杂度:O(n log n);其中:nboxTypes数组的长度。

四、代码实现

4.1> 先排序,再计算

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        int result = 0;
        Arrays.sort(boxTypes, Comparator.comparingInt(o -> o[1]));
        for (int i = boxTypes.length - 1; i >= 0; i--) {
            if (truckSize > boxTypes[i][0]) {
                result += boxTypes[i][0] * boxTypes[i][1];
                truckSize -= boxTypes[i][0];
            } else {
                result += truckSize * boxTypes[i][1];
                return result;
            }
        }
        return result;
    }
}

4.2> 通过数组实现排序,再计算

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        int result = 0;
        int[] type = new int[1001]; // index:箱子可以装载的单元数量  type[index]:index类型的箱子的数量
        for (int[] boxType : boxTypes) type[boxType[1]] += boxType[0];
        for (int i = type.length - 1; i >= 0; i--) {
            if (type[i] == 0) continue;
            if (truckSize > type[i]) {
                result += i * type[i];
                truckSize -= type[i];
            } else {
                result += i * truckSize;
                return result;
            }
        }
        return result;
    }
}

今天的文章内容就这些了:

写作不易,笔者几个小时甚至数天完成的一篇文章,只愿换来您几秒钟的 点赞 & 分享 。

更多技术干货,欢迎大家关注公众号“爪哇缪斯” ~ \(^o^)/ ~ 「干货分享,每天更新」

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值