223. Rectangle Area

Total Accepted: 38216 Total Submissions: 126941 Difficulty: Easy

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.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.


分析:

題意爲給定兩個矩形的對角座標,求解兩矩形所形成的面積大小。

本題參考博客:http://blog.csdn.net/pistolove/article/details/46868363

兩個矩形要麼重疊,要麼不重疊!

先假設存在重疊,接着計算出重疊的四個角的座標,如果滿足大小關係(見代碼)則存在,就減去重疊部分的面積。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int result=(D-B)*(C-A)+(H-F)*(G-E);
        //求取重疊部分的四個角座標
        int left = max(A, E);  
        int down = max(B, F);  
        int right = min(G, C);  
        int up = min(D, H);  
  
        if (up <= down || right <= left) //沒有重疊
            return result;  
    
        return  result - (right - left) * (up - down);
    }
};

注:本博文爲EbowTang原創,後續可能繼續更新本文。如果轉載,請務必複製本條信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51546418

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode題解索引:http://blog.csdn.net/ebowtang/article/details/50668895

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章