LeetCode -- Rectangle Area

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.

Rectangle Area

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;    
    }

}

 

posted @ 2015-10-17 11:26  江湖小妞  阅读(293)  评论(0编辑  收藏  举报