题目:
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) {
bool rc1IsEmpty = D <= B || C <= A;
bool rc2IsEmpty = H <= F || G <= E;
if (rc1IsEmpty && rc2IsEmpty) {
return 0;
} else if (rc1IsEmpty) {
return (H - F) * (G - E);
} else if (rc2IsEmpty) {
return (D - B) * (C - A);
}
int size;
if(B >= H || F >= D || E >= C || A >= G) {
size = 0;
}
else {
int dx = (H < D ? H : D) - (F > B ? F : B);
int dy = (C < G ? C : G) - (A > E ? A : E);
size = dx * dy;
}
return (H - F) * (G - E) + (D - B) * (C - A) - size;
}
};