223. Rectangle Area

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.

rectangle area
Assume that the total area is never beyond the maximum possible value of int.

解法1:

lang: java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int left = (C - A) * (D - B);
int right = (G - E) * (H - F);
// on the left or right side
if (E >= C || G <= A) {
return left + right;
}
// above or below
if (F >= D || H <= B ) {
return left + right;
}
// overlap
int ldx = Math.max(A, E);
int ldy = Math.max(B, F);
int rux = Math.min(C, G);
int ruy = Math.min(D, H);
int cross = (rux - ldx) * (ruy - ldy);
return left + right - cross;
}
}