矩形面积
难度:
标签:
题目描述
给你 二维 平面上两个 由直线构成且边与坐标轴平行/垂直 的矩形,请你计算并返回两个矩形覆盖的总面积。
每个矩形由其 左下 顶点和 右上 顶点坐标表示:
- 第一个矩形由其左下顶点
(ax1, ay1)
和右上顶点(ax2, ay2)
定义。 - 第二个矩形由其左下顶点
(bx1, by1)
和右上顶点(bx2, by2)
定义。
示例 1:

输入:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 输出:45
示例 2:
输入:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 输出:16
提示:
-104 <= ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 <= 104
代码结果
运行时间: 34 ms, 内存: 16.2 MB
/*
* Problem Statement:
* Given two rectangles on a 2D plane where the edges are parallel or perpendicular to the axes,
* calculate and return the total area covered by both rectangles.
* Each rectangle is defined by its bottom-left vertex (ax1, ay1) and top-right vertex (ax2, ay2)
* and (bx1, by1) and (bx2, by2) for the second rectangle.
*/
import java.util.stream.IntStream;
public class RectangleAreaStream {
public static int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
// Calculate the area of the first rectangle
int area1 = (ax2 - ax1) * (ay2 - ay1);
// Calculate the area of the second rectangle
int area2 = (bx2 - bx1) * (by2 - by1);
// Calculate the overlapping area using streams
int overlapWidth = IntStream.of(ax2, bx2).min().getAsInt() - IntStream.of(ax1, bx1).max().getAsInt();
int overlapHeight = IntStream.of(ay2, by2).min().getAsInt() - IntStream.of(ay1, by1).max().getAsInt();
int overlapArea = (overlapWidth > 0 && overlapHeight > 0) ? overlapWidth * overlapHeight : 0;
// Total area is the sum of individual areas minus the overlapping area
return area1 + area2 - overlapArea;
}
public static void main(String[] args) {
// Example 1
System.out.println(computeArea(-3, 0, 3, 4, 0, -1, 9, 2)); // Output: 45
// Example 2
System.out.println(computeArea(-2, -2, 2, 2, -2, -2, 2, 2)); // Output: 16
}
}
解释
方法:
该题解的思路是分别计算两个矩形的面积,然后减去它们重叠部分的面积。重叠部分的宽度是两个矩形在 x 轴投影的交集,高度是 y 轴投影的交集。先计算交集的宽度 a 和高度 b,然后用两个矩形面积之和减去 a*b 即可得到最终结果。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
计算交集宽度和高度时,为什么要用max函数确保结果不小于0?
▷🦆
在计算两个矩形面积的和时,是否考虑了可能的整型溢出情况,特别是在语言如Java中?
▷🦆
您的代码在计算重叠面积时使用了min和max函数来确定边界,这种方法在所有情况下都能正确工作吗?
▷🦆
如果两个矩形没有任何重叠,算法的输出是否仍然正确,尤其是关于交集面积的计算?
▷相关问题
矩形重叠
矩形以列表 [x1, y1, x2, y2]
的形式表示,其中 (x1, y1)
为左下角的坐标,(x2, y2)
是右上角的坐标。矩形的上下边平行于 x 轴,左右边平行于 y 轴。
如果相交的面积为 正 ,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。
给出两个矩形 rec1
和 rec2
。如果它们重叠,返回 true
;否则,返回 false
。
示例 1:
输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3] 输出:true
示例 2:
输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1] 输出:false
示例 3:
输入:rec1 = [0,0,1,1], rec2 = [2,2,3,3] 输出:false
提示:
rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1
和rec2
表示一个面积不为零的有效矩形