您的位置:首页 > 其它

95-Rectangle Area

2016-05-27 14:05 232 查看
-223. Rectangle Area My Submissions QuestionEditorial Solution

Total Accepted: 37901 Total Submissions: 126073 Difficulty: Easy

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

Assume that the total area is never beyond the maximum possible value of int.

求两个矩形并集的总面积

思路:求出交集

利用容斥原理

|A⋃B|=|A|+|B|−|A⋂B|

考虑特殊用例:

比如矩形收缩为点

矩形收缩为线

矩形面积越界

整型求和越界

无交集

有交集

class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
long long resAx,resBy,resCx,resDy;
long long area1,area2,intersect=-1;
resAx= max(A,E);
resCx= min(C,G);
resBy=max(B,F);
resDy=min(D,H);//求出交集矩形对角点
if(resCx-resAx<=0||resDy-resBy<=0)intersect=0; //交集为空
else intersect = abs(resCx-resAx)*abs(resDy-resBy);
if((A==C||B==D)||(E==G)||F==H)intersect=0;//修补收缩为线的情况
area1=(C-A)*(D-B),area2 = (G-E)*(H-F);
return area1+area2-intersect;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: