LeetCode筆記:223. Rectangle Area

問(wèn)題:

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.


image.png

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

大意:

計(jì)算兩個(gè)2D矩形覆蓋的全部區(qū)域面積。
每個(gè)矩形都由圖中這種左下角和右上角的坐標(biāo)來(lái)定義。


image.png

假設(shè)整體區(qū)域不會(huì)大于整型的最大值。

思路:

一開(kāi)始弄錯(cuò)了,以為是計(jì)算重復(fù)面積,后來(lái)才發(fā)現(xiàn)是計(jì)算全部面積,其實(shí)也差不多,就是用兩個(gè)矩形的面積和減去重復(fù)覆蓋的面積。

計(jì)算面積其實(shí)很容易,關(guān)鍵在于判斷各種可能的情況,判斷有沒(méi)有重復(fù)覆蓋的面積,以及如何去準(zhǔn)確的計(jì)算,題目給的用例實(shí)在是任性,說(shuō)好的左下角和右上角,G,H的值卻可能比E,F要小= =

做過(guò)這道題后不得不說(shuō)坐標(biāo)的計(jì)算真的要細(xì)心并且考慮周全啊,好多粗心犯的錯(cuò)誤。

代碼(Java):

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        if (A > C) {
            int temp = A;
            A = C;
            C = temp;
        }
        if (B > D) {
            int temp = B;
            B = D;
            D = temp;
        }
        if (E > G) {
            int temp = E;
            E = G;
            G = temp;
        }
        if (F > H) {
            int temp = F;
            F = H;
            H = temp;
        }
        
        int width1 = Math.abs(C - A);
        int height1 = Math.abs(D - B);
        int width2 = Math.abs(G - E);
        int height2 = Math.abs(H - F);
        
        // 兩個(gè)長(zhǎng)方形面積
        int area1 = width1 * height1;
        int area2 = width2 * height2;
        
        // 計(jì)算重合部分
        // 重合部分為0
        if (A + width1 <= E || E + width2 <= A || B + height1 <= F || F + height2 <= B) return area1 + area2;
        // 重合部分不為0
        int width;
        if (E == A) width = Math.min(width1, width2);
        else if (E > A) width = Math.abs(E - A) + width2 < width1 ? width2 : width1 - Math.abs(E - A);
        else width = Math.abs(A - E) + width1 < width2 ? width1 : width2 - Math.abs(A - E);
        
        int height;
        if (F == B) height = Math.min(height1, height2);
        else if (F > B) height = Math.abs(F - B) + height2 < height1 ? height2 : height1 - Math.abs(F - B);
        else height = Math.abs(B - F) + height1 < height2 ? height1 : height2 - Math.abs(B - F);
        
        return area1 + area2 - width * height;
    }
}

他山之石:

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int left = Math.max(A,E), right = Math.max(Math.min(C,G), left);
        int bottom = Math.max(B,F), top = Math.max(Math.min(D,H), bottom);
        return (C-A)*(D-B) - (right-left)*(top-bottom) + (G-E)*(H-F);
    }
}

這個(gè)計(jì)算重復(fù)面積的方式很巧妙,簡(jiǎn)單多了。

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁(yè)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容