[LeetCode] 223. Rectangle Area 矩形面積

 

Find the total area covered by two rectilinearrectangles in a 2D plane.html

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.git

Rectangle Area

Example:github

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 Output: 45

Note:post

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

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.url

 

這道題不算一道很難的題,但博主仍是花了好久才作出來,剛開始嘗試找出因此有重疊的狀況,發現有不少種狀況,很麻煩。後來換了一種思路,嘗試先找出全部的不相交的狀況,只有四種,一個矩形在另外一個的上下左右四個位置不重疊,這四種狀況下返回兩個矩形面積之和。其餘全部狀況下兩個矩形是有交集的,這時候只要算出長和寬,便可求出交集區域的大小,而後從兩個矩型面積之和中減去交集面積就是最終答案。求交集區域的長和寬也不難,因爲交集都是在中間,因此橫邊的左端點是兩個矩形左頂點橫座標的較大值,右端點是兩個矩形右頂點的較小值,同理,豎邊的下端點是兩個矩形下頂點縱座標的較大值,上端點是兩個矩形上頂點縱座標的較小值。以前是能夠直接將 sum1 和 sum2 加起來的,能夠後來OJ搞了些噁心的 test case,使得直接把 sum1 和 sum2 相加會溢出,因此只好分開了,若兩個矩形有重疊,那麼返回的時候也不能讓 sum1 和 sum2 直接相加,中間必定要先減去重疊部分才行,代碼以下:spa

 

解法一:code

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int sum1 = (C - A) * (D - B), sum2 = (H - F) * (G - E);
        if (E >= C || F >= D || B >= H || A >= G) return sum1 + sum2;
        return sum1 - ((min(G, C) - max(A, E)) * (min(D, H) - max(B, F))) + sum2;
    }
};

 

本來上面解法的三行還能夠喪心病狂地合成一行,可是因爲 OJ 使壞,加了些變態的 test case,使得咱們仍是得拆分開來,先求出重疊區間的四個點 left,bottom,right,top 的值,而後再求出重疊區間的面積,避免溢出,參見代碼以下:htm

 

解法二:blog

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), right = max(min(C,G), left);
        int bottom = max(B,F), top = max(min(D,H), bottom);
        return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F);
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/223

 

相似題目:

Rectangle Overlap

Rectangle Area II

 

參考資料:

https://leetcode.com/problems/rectangle-area/

https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way

https://leetcode.com/problems/rectangle-area/discuss/62302/Clean-C%2B%2B-Solution-with-Detailed-Explanations

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索