您的位置:首页 > 大数据 > 人工智能

LeetCode OJ——Submission Details

2015-11-22 21:54 579 查看
题目:

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 s1 = (C - A) * (D - B);
int s2 = (G - E) * (H - F);
int point_low[2] = { 0 };
int point_high[2] = { 0 };

//先判断x轴的坐标关系A-C与E-G
if (G <= A) //第二个矩形在第一个矩形的左边,两者不相交
{
return s1 + s2;
}

if (G >A && G <= C) //第二个矩形与第一个矩形可能有重叠的部分
{
if (H <= B || F >= D)  //第二个矩形与第一个矩形不重叠
{
return s1 + s2;
}
else{
point_high[0] = (G < C) ? G : C;
point_high[1] = (H < D) ? H : D;
point_low[0] = (E > A) ? E : A;
point_low[1] = (F > B) ? F : B;

return (s1 + s2 - (point_high[0] - point_low[0]) * (point_high[1] - point_low[1]));

}
}

if (G > C)   //第二个矩形与第一个矩形可能有重叠的部分
{
if (E >= C)  //第二个矩形与第一个矩形不重叠
{
return s1 + s2;
}
else{      //第二个矩形与第一个矩形可能有重叠的部分
if (F >= D || H < B)        //第二个矩形与第一个矩形不重叠
{
return s1 + s2;
}
else{
point_high[0] = (G < C) ? G : C;
point_high[1] = (H < D) ? H : D;
point_low[0] = (E > A) ? E : A;
point_low[1] = (F > B) ? F : B;
}
return (s1 + s2 - (point_high[0] - point_low[0]) * (point_high[1] - point_low[1]));
}
}

}
};


结果:



思路:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: