您的位置:首页 > 其它

LeetCode *** 223. Rectangle Area

2016-04-09 21:08 316 查看
题目:

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 aLength=C-A,aWidth=D-B;
int bLength=G-E,bWidth=H-F;

int area1=aLength*aWidth;
int area2=bLength*bWidth;

if((G>A&&E>=C)||(C>E&&A>=G)||(D>F&&B>=H)||(H>B&&F>=D))
return area1+area2;
else{
int length=aLength+bLength-max(A,C,E,G)+min(A,C,E,G);
int width=aWidth+bWidth-max(B,D,F,H)+min(B,D,F,H);
return area1+area2-length*width;
}

}

int max(int a,int b,int c,int d){
int res1,res2;
res1=a>b?a:b;
res2=c>d?c:d;
return res1>res2?res1:res2;
}

int min(int a,int b,int c,int d){
int res1,res2;
res1=a<b?a:b;
res2=c<d?c:d;
return res1<res2?res1:res2;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: