# [Leetcode] 223. Rectangle Area 解题报告

174人阅读 评论(0)

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.

1、自己的代码：

class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area1 = (C - A) * (D - B);
int area2 = (G - E) * (H - F);
if (E >= C || G <= A || H <= B || F >= D) {     // no overlap
return area1 + area2;
}
int width = 0, height = 0;
if (E < A) {                                    // update width
width = G < C ? (G - A) : (C - A);
}
else {
width = G < C ? (G - E) : (C - E);
}
if (F < B) {                                    // update height
height = H < D ? (H - B) : (D - B);
}
else {
height = H < D ? (H - F) : (D - F);
}
return area1 + area2 - width * height;
}
};

2、别人的代码：

class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area = (C - A) * (D - B) + (G - E) * (H - F);
if(!(B >= H || F >= D || A >= G ||E >= C)) {
int tem = (min(C, G) - max(A, E)) * (min(D, H) -max(B, F));
area -= tem;
}
return area;
}
};
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int left = max(A, E), right = max(min(C, G), left);
int bot = max(B, F), top = max(min(D, H), bot);
return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bot);
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：88363次
• 积分：6321
• 等级：
• 排名：第4462名
• 原创：558篇
• 转载：10篇
• 译文：2篇
• 评论：17条
阅读排行
最新评论