LeetCode -- Rectangle Area

來源:互聯網
上載者:User

標籤:

Question:

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.

 

 Analysis:

問題描述:計算在二維座標系中兩個矩陣覆蓋的面積。每個矩陣由它的左下角和右上方的座標表示。

思路:關鍵是求兩個矩陣的相交部分的面積。有3種情況:一種是無相交的部分;一種是只有橫向和縱向的相交部分,一種是橫向和縱向都有相交部分。然而,由圖形可知,(A,B)的座標一定是小於(C,D),(E,F)的座標一定小於(G,H)。因此看有無相交時,只需要取兩個矩形中左下角中較大的作為新矩形的左下角座標和右上方中較小的作為新矩形的右上方座標,若新的矩形中右上方的座標還要比左下角的座標小,則說明原來的兩個矩形不相交,反之則相交。

PS:在計算矩陣面積的過程中,注意int型座標的計算是否會越界。

 

Answer:

public class Solution {    public static int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        int t1 = Math.max(A, E), t2 = Math.max(B, F), t3 = Math.min(C, G), t4 = Math.min(D, H);        int area1 = getArea(A, B, C, D);        int area2 = getArea(E, F, G, H);        int area3 = getArea(t1, t2, t3, t4);        if(t1 > t3 || t2 > t4)            return area1 + area2;        else             return area1 + area2 - area3;                        }        public static int getArea(int A, int B, int C, int D) {        int length = 0, wide = 0;        double t1 = (double)A * (double)C, t2 = (double)B * (double)D;        if(t1 >= 0)             length = Math.abs(Math.abs(A) - Math.abs(C));        else            length = Math.abs(A) + Math.abs(C);        if(t2 >= 0)             wide = Math.abs(Math.abs(B) - Math.abs(D));        else            wide = Math.abs(B) + Math.abs(D);        return length * wide;        }}

 

LeetCode -- Rectangle Area

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.