在二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。
每个矩形由其左下顶点和右上顶点坐标表示,如图所示。
示例:
输入: -3, 0, 3, 4, 0, -1, 9, 2
输出: 45
说明: 假设矩形面积不会超出 int 的范围。
答案:
1public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
2 int areaOfSqrA = (C - A) * (D - B);
3 int areaOfSqrB = (G - E) * (H - F);
4 int left = Math.max(A, E);
5 int right = Math.min(G, C);
6 int bottom = Math.max(F, B);
7 int top = Math.min(D, H);
8 //如果有重叠
9 int overlap = 0;
10 if (right > left && top > bottom)
11 overlap = (right - left) * (top - bottom);
12 return areaOfSqrA + areaOfSqrB - overlap;
13}
解析:
这题不是很难,可能有点复杂,自己就画个图慢慢体会。下面再来看一种解法
1public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
2 int total = (D - B) * (C - A) + (H - F) * (G - E);
3 if (!(A < G && E < C && B < H && F < D))
4 return total;
5 int right = Math.min(D, H), left = Math.max(B, F), top = Math.min(C, G), bottom = Math.max(A, E);
6 return total - (right - left) * (top - bottom);
7}