LeetCode #223 - Rectangle Area - Easy

来源:互联网 发布:2016淘宝商品排行榜 编辑:程序博客网 时间:2024/05/19 14:17

Problem

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.

Example

Rectangle Area
Rectangle Area


Algorithm

整理一下题意:给定二维平面上两个两边与坐标轴平行的矩形,要求返回他们在平面上所占用的面积。假设所有坐标都是整数且在int定义的范围内。

数学题,其实只要把所有情况都考虑到就可以了。所占用的面积等于两个矩形面积之和减去重合面积,于是只要求重合部分的面积即可。可利用数轴来考虑全部情况。

代码如下。

class Solution {public:    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        int x,y;        if(C<=E) x=0;        if(A<=E&&E<C&&C<=G) x=C-E;        if(E<A&&A<=G&&G<C) x=G-A;        if(E<A&&C<=G) x=C-A;        if(A<=E&&G<C) x=G-E;        if(G<=A) x=0;        if(D<=F) y=0;        if(B<=F&&F<D&&D<=H) y=D-F;        if(F<B&&B<=H&&H<D) y=H-B;        if(F<B&&D<=H) y=D-B;        if(B<=F&&H<D) y=H-F;        if(H<=B) y=0;        return abs(A-C)*abs(B-D)+abs(E-G)*abs(F-H)-x*y;    }};
0 0
原创粉丝点击