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

223. Rectangle Area

时间:2015-11-25 06:37:50      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

链接: http://leetcode.com/problems/rectangle-area/

题解:

数学题,需要判断矩阵是否相交,相交的话减去重复面积(顶点相交除外)。

Time Complexity - O(1), Space Complexity - O(1)。

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area = (C - A) * (D - B) + (G - E) * (H - F);
        if(A >= G || B >= H || C <= E || D <= F)
            return area;
        
        int duplicate = (Math.min(C, G) - Math.max(A, E)) * (Math.min(D, H) - Math.max(B, F));
        return area - duplicate;
    }
}

 

Reference:

https://leetcode.com/discuss/39188/an-easy-to-understand-solution-in-java

https://leetcode.com/discuss/39398/my-java-solution-sum-of-areas-overlapped-area

https://leetcode.com/discuss/43549/just-another-short-way

https://leetcode.com/discuss/43173/if-you-want-to-laugh-look-at-my-solution

https://leetcode.com/discuss/54138/python-concise-solution

https://leetcode.com/discuss/51354/an-explanation-in-plain-language

223. Rectangle Area

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4993512.html

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