根据规则将箱子分类
难度:
标签:
题目描述
Given four integers length
, width
, height
, and mass
, representing the dimensions and mass of a box, respectively, return a string representing the category of the box.
- The box is
"Bulky"
if:- Any of the dimensions of the box is greater or equal to
104
. - Or, the volume of the box is greater or equal to
109
.
- Any of the dimensions of the box is greater or equal to
- If the mass of the box is greater or equal to
100
, it is"Heavy".
- If the box is both
"Bulky"
and"Heavy"
, then its category is"Both"
. - If the box is neither
"Bulky"
nor"Heavy"
, then its category is"Neither"
. - If the box is
"Bulky"
but not"Heavy"
, then its category is"Bulky"
. - If the box is
"Heavy"
but not"Bulky"
, then its category is"Heavy"
.
Note that the volume of the box is the product of its length, width and height.
Example 1:
Input: length = 1000, width = 35, height = 700, mass = 300 Output: "Heavy" Explanation: None of the dimensions of the box is greater or equal to 104. Its volume = 24500000 <= 109. So it cannot be categorized as "Bulky". However mass >= 100, so the box is "Heavy". Since the box is not "Bulky" but "Heavy", we return "Heavy".
Example 2:
Input: length = 200, width = 50, height = 800, mass = 50 Output: "Neither" Explanation: None of the dimensions of the box is greater or equal to 104. Its volume = 8 * 106 <= 109. So it cannot be categorized as "Bulky". Its mass is also less than 100, so it cannot be categorized as "Heavy" either. Since its neither of the two above categories, we return "Neither".
Constraints:
1 <= length, width, height <= 105
1 <= mass <= 103
代码结果
运行时间: 22 ms, 内存: 16.0 MB
/*
* This solution uses Java Stream API to determine the category of a box based on its dimensions and mass.
* - Stream.of() is used to process the dimensions to check if any of them are greater than or equal to 10^4.
* - The volume is calculated using reduce() and checked against 10^9.
* - The box is categorized similarly as in the non-stream solution.
*/
import java.util.stream.Stream;
public class BoxCategoryStream {
public static String categorizeBox(int length, int width, int height, int mass) {
boolean bulky = Stream.of(length, width, height).anyMatch(dim -> dim >= 10000) || (long)length * width * height >= 1000000000;
boolean heavy = mass >= 100;
if (bulky && heavy) return "Both";
if (bulky) return "Bulky";
if (heavy) return "Heavy";
return "Neither";
}
}
解释
方法:
首先,计算箱子的体积和最大维度。接着,根据题目条件判断箱子是否是'Bulky'(至少一个维度大于等于104或体积大于等于109)。再检查箱子的质量是否大于等于100,从而判断是否是'Heavy'。最后,根据箱子是否满足'Bulky'和'Heavy'的条件,返回相应的分类字符串。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么算法中判断是否为'Bulky'的条件是维度大于等于10000而不是104?
▷🦆
在计算体积时,有没有考虑体积计算可能导致的整数溢出的问题?
▷🦆
在判断箱子的类别时,代码先判断'Bulky'和'Heavy'都满足的情况,这种顺序是否有特殊的考虑?
▷🦆
如果输入的维度或质量是负数,这个算法是否还能正确运作?应该如何处理这种情况?
▷