对角线最长的矩形的面积
难度:
标签:
题目描述
You are given a 2D 0-indexed integer array dimensions
.
For all indices i
, 0 <= i < dimensions.length
, dimensions[i][0]
represents the length and dimensions[i][1]
represents the width of the rectangle i
.
Return the area of the rectangle having the longest diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the maximum area.
Example 1:
Input: dimensions = [[9,3],[8,6]] Output: 48 Explanation: For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈ 9.487. For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10. So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
Example 2:
Input: dimensions = [[3,4],[4,3]] Output: 12 Explanation: Length of diagonal is the same for both which is 5, so maximum area = 12.
Constraints:
1 <= dimensions.length <= 100
dimensions[i].length == 2
1 <= dimensions[i][0], dimensions[i][1] <= 100
代码结果
运行时间: 20 ms, 内存: 16.7 MB
/*
题目思路:
1. 使用Java Stream计算每个矩形的对角线长度和面积。
2. 根据对角线长度和面积找到最大的矩形面积。
*/
import java.util.Arrays;
public class Solution {
public int maxRectangleArea(int[][] dimensions) {
return Arrays.stream(dimensions)
.mapToInt(d -> {
double diagonal = Math.sqrt(d[0] * d[0] + d[1] * d[1]);
int area = d[0] * d[1];
return (int) (diagonal * 10000) + area;
})
.max()
.orElse(0) % 10000;
}
}
解释
方法:
该题解首先通过计算每个矩形的对角线长度的平方来避免使用浮点运算。它创建一个新的列表,包含每个矩形的对角线长度平方、长度和宽度。接着,题解通过对这个列表进行排序,优先按对角线长度平方降序排列,如果对角线长度相同,则按面积降序排列。排序后,列表的第一个元素即是对角线最长且(在长度相同的情况下)面积最大的矩形。最后,计算并返回这个矩形的面积。
时间复杂度:
O(n log n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么选择使用对角线长度的平方而不是直接计算对角线长度进行比较?
▷🦆
在排序时使用lambda函数进行复合排序(先按对角线平方长度,再按面积大小),这种排序方式是否确保了在对角线长度相同的情况下总能得到最大的面积?
▷🦆
如何处理所有矩形对角线长度平方和面积都相同的极端情况?
▷🦆
给定的解法中,如果输入的dimensions列表为空,该如何处理?
▷