首页 > 其他 > 详细

[LeetCode#223]Rectangle Area

时间:2015-08-29 09:34:46      阅读:100      评论:0      收藏:0      [点我收藏+]

Problem:

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:

The seems complex problem could be easily analyzed and sovled through simple analysis. 
If you try to analyze and distinguish in the scope of rectangle, it is too crazy to clear the relationship between them. 

But we could actually do it in a very simple way. We analyze the prolem through two separate direction: vertical direction and horizontal direction.
Principle: Once rectangle A in connected rectangle B, there must be a overlay either in vertical direction or horizontal direction. Otherwise they could not overlay with each other. 

The horizontal direction:
A-------------------- C

        E--------------------------G
        
        
E-------------------- G
        A------------------------C

If the two rectangles overlay with each other, at horizontal direction, it must meet one the above situation.
If not, they are not overlay.
        if (A > G || C < E)
            return (H-F)*(G-E) + (D-B)*(C-A);

We could also see that, since A is the left edge of C, E is the left edge of G,
The left coordinate for the overlaied rectangles is :
---------------------------------------------------
int left = Math.max(A, E);
The right coordinate for the overlaied rectangles is :
-------------------------------------------------------
int right = Math.min(C, G);

The same analysis could apply to the vertical direction.

Skill:
To compute the overall area, we could use: total area - overlaid area.

Solution:

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

 

[LeetCode#223]Rectangle Area

原文:http://www.cnblogs.com/airwindow/p/4768348.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!