LeetCode #223 - Rectangle Area - Easy

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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章