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.
[分析]
常规思路:判断两个矩形是否有重叠,无重叠返回面积加和即可,有重叠检查是否是包含关系,包含关系返回大面积,不是包含关系的面积加和减去重叠域面积。
非常规思路:参考https://leetcode.com/discuss/43549/just-another-short-way
public class Solution {
// Method 2
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 bottom = max(B,F), top = max(min(D,H), bottom);
return (C-A)*(D-B) - (right-left)*(top-bottom) + (G-E)*(H-F);
}
// Method 1
public int computeArea1(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 (G <= A || C <= E || D <= F || H <= B) return area1 + area2;
if ((A <= E && G <= C) && (B <= F && H <= D)) return area1;
if ((E <= A && C <= G) && (F <= B && D <= H)) return area2;
int xOverlap = getOverlap(A, C, E, G);
int yOverlap = getOverlap(B, D, F, H);
return area1 + area2 - xOverlap * yOverlap;
}
public int getOverlap(int a1, int a2, int b1, int b2) {
if (a1 <= b1 && b2 <= a2) return b2 - b1;
if (b1 <= a1 && a2 <= b2) return a2 - a1;
if (a1 <= b1 && b1 <= a2) return a2 - b1;
if (a1 <= b2 && b2 <= a2) return b2 - a1;
return 0;
}
}
本文介绍了一种计算二维平面上两个矩形总面积的方法,包括判断矩形间是否有重叠区域,以及如何准确计算非重叠与重叠情况下的总面积。
973

被折叠的 条评论
为什么被折叠?



