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;
}
};