LEETCODE-Rectangle Area

来源:互联网 发布:像一世之尊的小说知乎 编辑:程序博客网 时间:2024/06/01 08:05

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.

这里写图片描述
就是先判断两矩形的相对关系,是否相离(两矩形面积直接相加),相交(两矩形面积相加之后再减掉重合部分面积),包含(直接返回包含矩形的面积);
再根据不同的关系进行计算;

class Solution {public:int Max(int x, int y) {        if (x > y)            return x;        else            return y;    }    int Min(int x, int y) {        if (x < y)            return x;        else            return y;    }    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        if (E > C || A > G || B > H || F > D)        return (C - A)*(D - B) + (G - E)*(H - F);        int xleftdown = Max(A, E);        int yleftdown = Max(B, F);        int xrightup = Min(C, G);        int yrightup = Min(D, H);        if (xleftdown == E && yleftdown == F && xrightup == G && yrightup == H)            return (C - A)*(D - B);        else if (xleftdown == A && yleftdown == B && xrightup == C && yrightup == D)            return (G - E)*(H - F);        else            return (C - A)*(D - B) + (G - E)*(H - F)-(xrightup - xleftdown)*(yrightup - yleftdown);    }};
1 0