题目描述:
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

Assume that the total area is never beyond the maximum possible value of int.
计算两个矩形覆盖的总面积=矩形1面积+矩形2面积-重叠面积。
当F>=D||H<=B||E>=C||G<=A时,重叠区域为0.
代码如下:
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int overlapArea=0;
if(F>=D||H<=B||E>=C||G<=A)
overlapArea=0;
else{
int newA=Integer.max(A, E);
int newB=Integer.max(B, F);
int newC=Integer.min(C, G);
int newD=Integer.min(D, H);
overlapArea=(newC-newA)*(newD-newB);
}
return (C-A)*(D-B)+(G-E)*(H-F)-overlapArea;
}
}
本文介绍了一种计算二维平面上两个矩形重叠面积的方法,并提供了一个具体的实现示例。通过判断矩形的位置关系来计算重叠部分的面积。
818

被折叠的 条评论
为什么被折叠?



