题目描述:
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.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
Hide Tags Math
分析:
乍一看,题目比较复杂。两个矩形的位置是任意的,如果不相交,则直接返回两个矩形的和;
如果相交,那么相交的情况有多种,但是最后返回的面积都是两个大矩形的面积减去交叉矩形的面积。
那么重点就是求交叉矩形的面积了。
根据两个大矩形的坐标,是可以得到交叉矩形四个点的坐标的。
其中交叉矩形的较大纵坐标up是两个矩形对应较大纵坐标的较小值
较小纵坐标down是两个矩形各对应小纵坐标的较大值
较小横坐标lef是是两个矩形各对应小横坐标的较大值
较大横坐标rig是是两个矩形各对应大横坐标的较小值
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.
Rectangle Area
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
Hide Tags Math
分析:
乍一看,题目比较复杂。两个矩形的位置是任意的,如果不相交,则直接返回两个矩形的和;
如果相交,那么相交的情况有多种,但是最后返回的面积都是两个大矩形的面积减去交叉矩形的面积。
那么重点就是求交叉矩形的面积了。
根据两个大矩形的坐标,是可以得到交叉矩形四个点的坐标的。
其中交叉矩形的较大纵坐标up是两个矩形对应较大纵坐标的较小值
较小纵坐标down是两个矩形各对应小纵坐标的较大值
较小横坐标lef是是两个矩形各对应小横坐标的较大值
较大横坐标rig是是两个矩形各对应大横坐标的较小值
以下是C++实现代码:
/**0ms*/
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int a = 0, b = 0,c = 0;
a = (C - A)*(D - B);
b = (G - E)*(H - F);
if(C <= E || A >= G || B >= H ||F >=D ) //不相交
{
return a+b;
}
//相交,求出交叉矩形的边长
int up = min(H,D);
int down = max(B,F);
int lef = max(A,E);
int rig = min(G,C);
c = (up-down) * (rig - lef); //交叉矩形的面积
return a + b - c;
}
};