原题地址:https://leetcode-cn.com/problems/rectangle-area/submissions/
题目描述:
在二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。
每个矩形由其左下顶点和右上顶点坐标表示,如图所示。
Rectangle Area
示例:
输入: -3, 0, 3, 4, 0, -1, 9, 2
输出: 45
说明: 假设矩形面积不会超出 int 的范围。
解题方案:
本题就是一道数学题,需要找到规律。自己找了半天,实在是太笨了。。
代码:
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int left = max(A, E);
int right = min(C, G);
int up = min(D, H);
int down = max(B, F);
int repeat = 0;
if(right > left && up > down)
repeat = (right - left) * (up - down);
return (C-A) * (D-B) + (G-E) * (H-F) - repeat;
}
};