码迷,mamicode.com
首页 > 其他好文 > 详细

Rectangle Area

时间:2015-06-08 21:35:34      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:rectangle   area   相交   

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.

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

思路:
见下图。

技术分享
代码如下:

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area1=(D-B)*(C-A);
        int area2=(H-F)*(G-E);
        int totalWith=(C-A)+(G-E);
        int totalHeight=(D-B)+(H-F);
        int[] w=findMaxAndMin(new int[]{A,E,C,G});
        int maxWidthDis=w[0]-w[1];//在X轴上投影,获得实际宽度
        int[] h=findMaxAndMin(new int[]{F,B,H,D});
        int maxHeightDis=h[0]-h[1];//在Y轴上投影,获得实际高度
        if(maxWidthDis>totalWith||maxHeightDis>totalHeight){//不相交
            return area1+area2;
        }
        return area1+area2-(totalWith-maxWidthDis)*(totalHeight-maxHeightDis);//减去阴影面积
    }
    //b[0]保存最大值,b[1]保存最小值
    private int[] findMaxAndMin(int[] a){
        int[] b = new int[2];
        b[0]=b[1]=a[0];
        for(int i=1;i<a.length;i++){
            if(a[i]>b[0]){
                b[0]=a[i];
            }else if(a[i]<b[1]){
                b[1]=a[i];
            }
        }
        return b;
    }
}

Rectangle Area

标签:rectangle   area   相交   

原文地址:http://blog.csdn.net/u010786672/article/details/46417935

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!