问题:
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.
解决:
① 该问题可以看作内部重叠问题, 在x轴上有(A,C)和(E,G); 在Y轴上有(F,H)和(B,D)。 如果它们没有重叠,则总面积是2个矩形区域的总和。 如果它们有重叠,总面积应该减去重叠面积。
class Solution { //5ms
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
if (C < E || G < A){
return (G - E) * (H - F) + (C - A) * (D - B);
}
if (D < F || H < B){
return (G - E) * (H - F) + (C - A) * (D - B);
}
int right = Math.min(C,G);
int left = Math.max(A,E);
int top = Math.min(H,D);
int bootom = Math.max(F,B);
return (G - E) * (H - F) + (C - A) * (D - B) - (right - left) * (top - bootom);
}
}
②
public class Solution { //4ms
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);
area += (G - E) * (H - F);
if (A >= G || E >= C || B >= H || D <= F) {
return area;
}
int x1 = A > E ? A : E;
int x2 = C < G ? C : G;
int y1 = B > F ? B : F;
int y2 = D < H ? D : H;
return area - (x2 - x1) * (y2 - y1);
}
}