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.
题目:要求求出两个矩形区域的总面积
方法:两个矩形面积相加,然后减去可能存在的相交区域。
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int xMin,xMax,yMin,yMax; int sum=(C-A)*(D-B)+(G-E)*(H-F);//两个矩形,面积的直接和 //找到两个矩形的区域 xMin=A>E?A:E; xMax=C<G?C:G; yMin=B>F?B:F; yMax=D<H?D:H; if(xMax>xMin && yMax>yMin)//判断两个矩形是否真的存在此相交区域 sum-=(xMax-xMin)*(yMax-yMin);//存在,则减去相交区域面积 return sum; } };
时间: 2024-11-05 18:55:39