题目
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.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 Output: 45
Note:
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) {
int init = (C-A)*(D-B)+(G-E)*(H-F);
int up,down,left,right;
if(E>C||G<A||H<B||F>D) return init;
if(D>H) up=H;
else up=D;
if(B>F) down=B;
else down=F;
if(A>E) left=A;
else left=E;
if(C>G) right=G;
else right=C;
return init-(up-down)*(right-left);
}
}