[LeetCode] 223. Rectangle Area 矩形面積


 

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

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

Rectangle Area

Example:

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

Note:

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

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

 

這道題不算一道很難的題,但博主還是花了很久才做出來,剛開始嘗試找出所以有重疊的情況,發現有很多種情況,很麻煩。后來換了一種思路,嘗試先找出所有的不相交的情況,只有四種,一個矩形在另一個的上下左右四個位置不重疊,這四種情況下返回兩個矩形面積之和。其他所有情況下兩個矩形是有交集的,這時候只要算出長和寬,即可求出交集區域的大小,然后從兩個矩型面積之和中減去交集面積就是最終答案。求交集區域的長和寬也不難,由於交集都是在中間,所以橫邊的左端點是兩個矩形左頂點橫坐標的較大值,右端點是兩個矩形右頂點的較小值,同理,豎邊的下端點是兩個矩形下頂點縱坐標的較大值,上端點是兩個矩形上頂點縱坐標的較小值。之前是可以直接將 sum1 和 sum2 加起來的,可以后來OJ搞了些惡心的 test case,使得直接把 sum1 和 sum2 相加會溢出,所以只好分開了,若兩個矩形有重疊,那么返回的時候也不能讓 sum1 和 sum2 直接相加,中間一定要先減去重疊部分才行,代碼如下:

 

解法一:

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 的值,然后再求出重疊區間的面積,避免溢出,參見代碼如下:

 

解法二:

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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM