leetcode
leetcode 2751 ~ 2800
重新分装苹果

重新分装苹果

难度:

标签:

题目描述

You are given an array apple of size n and an array capacity of size m.

There are n packs where the ith pack contains apple[i] apples. There are m boxes as well, and the ith box has a capacity of capacity[i] apples.

Return the minimum number of boxes you need to select to redistribute these n packs of apples into boxes.

Note that, apples from the same pack can be distributed into different boxes.

 

Example 1:

Input: apple = [1,3,2], capacity = [4,3,1,5,2]
Output: 2
Explanation: We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.

Example 2:

Input: apple = [5,5,5], capacity = [2,4,2,7]
Output: 4
Explanation: We will need to use all the boxes.

 

Constraints:

  • 1 <= n == apple.length <= 50
  • 1 <= m == capacity.length <= 50
  • 1 <= apple[i], capacity[i] <= 50
  • The input is generated such that it's possible to redistribute packs of apples into boxes.

代码结果

运行时间: 19 ms, 内存: 16.1 MB


/*
 * 思路:
 * 1. 将容量数组按降序排序。
 * 2. 计算所有苹果的总数。
 * 3. 遍历容量数组并逐一使用容量最大的箱子装苹果,直到装完所有苹果。
 * 4. 返回使用的箱子数量。
 */

import java.util.Arrays;

public class Solution {
    public int minBoxes(int[] apple, int[] capacity) {
        Arrays.sort(capacity);
        int totalApples = Arrays.stream(apple).sum();
        int[] boxCount = {0};
        int[] currentCapacity = {0};

        Arrays.stream(capacity)
                .boxed()
                .sorted((a, b) -> b - a)
                .takeWhile(cap -> {
                    currentCapacity[0] += cap;
                    boxCount[0]++;
                    return currentCapacity[0] < totalApples;
                })
                .count();

        return boxCount[0];
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] apple = {1, 3, 2};
        int[] capacity = {4, 3, 1, 5, 2};
        System.out.println(sol.minBoxes(apple, capacity)); // 输出:2
    }
}

解释

方法:

该题解的主要思路是首先计算所有包裹中苹果的总数,然后将箱子的容量数组进行降序排序。通过遍历排序后的箱子容量数组,逐一从苹果总数中减去每个箱子的容量,直到苹果总数小于或等于零。这样,我们就能得到所需的最小箱子数量。该方法的核心在于优先使用容量大的箱子,以最大化每次装箱的苹果数量,从而减少所需箱子的数量。

时间复杂度:

O(m log m)

空间复杂度:

O(m)

代码细节讲解

🦆
算法中苹果总数 `t` 是否可能超出 `int` 类型的范围,导致计算错误?
在Python中,整数的类型是动态的,可以自动处理非常大的数值,因为Python整数类型 (`int`) 在需要时可以自动转换为长整数类型 (`long`),这几乎没有限制。因此,即使苹果的总数非常大,超出了传统意义上的32位或64位整数的最大值,Python仍然可以正确处理这些数值,无需担心溢出问题。
🦆
在箱子容量数组 `capacity` 降序排序后,如何保证这种排序方式总是得到最优解?
降序排序箱子的容量是基于贪心算法的思想,目的是尽可能快地减少苹果总数。通过优先使用容量最大的箱子,可以在使用较少的箱子数目的情况下装下更多的苹果。这种方法在求解最小箱子数目问题时是有效的,因为每一步都尽可能最大地减少剩余苹果数,从而达到整体的最优解。
🦆
如果存在某些箱子的容量为 0,算法是否还能正确处理?
容量为0的箱子对于装苹果没有任何贡献,可以在算法实际运行前从容量数组中移除,或者在遍历容量时简单地忽略这些箱子。这样做不会影响算法的正确性或最终结果,因为这些箱子不会对减少苹果总数或计算所需箱子数量产生任何影响。

相关问题