题目链接: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.
![]()
Assume that the total area is never beyond the maximum possible value of int.
(1)思路:这题相对比较简单,用两个长方形面积之和减去重合部分面积就是总面积。但是提交时发现只能使用类似a<
b来判断a、b大小,不能使用c = a - b这样的c来判断是否小于0,会溢出。
(2)代码:
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int a1 = (C - A) * (D - B);
int a2 = (G - E) * (H - F);
int w1 = max(A, E);
int w2 = min(C, G);
int w = w2 - w1;
int h1 = max(B, F);
int h2 = min(D, H);
int h = h2 -h1;
if(h2 < h1 || w2 < w1) return (a1 + a2);
else return (a1 + a2 - w * h);
}
};