223. Rectangle Area
2016-09-17 本文已影响0人
a_void
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.
Idea: be aware of number overflow
class Solution {
public:
void swap(int &a, int &b){
int t = a;
a = b;
b = t;
}
int max(int a, int b){
return a > b ? a : b;
}
int min(int a, int b){
return a > b ? b : a;
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
// order points
if(A > C) swap(A, C);
if(B > D) swap(B, D);
if(E > G) swap(E, G);
if(F > H) swap(F, H);
//
int sum = (C - A) * (D - B) + (G - E) * (H - F);
int h1 = min(C, G), h2 = max(A, E);
int v1 = min(D, H), v2 = max(B, F);
int over = 0;
if(h1 > h2 && v1 > v2) over = (h1 - h2) * (v1 - v2);
return sum - over;
}
};