Leetcode_223_Rectangle Area
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode_223_Rectangle Area相关的知识,希望对你有一定的参考价值。
本文是在学习中的总结。欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46868363
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.
![技术分享](https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum possible value of int.
思路:
(1)题意为给定两个矩形的对角坐标,求解两矩形所形成的面积大小。
(2)该题比較简单。最開始对其进行分析时,考虑的比較复杂。
考虑到两个矩形之间的关系无非包括三种:相离、相交、包括。
对于相离,仅仅须要判定当中一个矩形的横、纵坐标的最小值大于还有一个的最大值就可以。对于包括。仅仅需判定当中一个矩形的两个顶点坐标范围是否在还有一个矩形中就可以。对于包括,略微有一点复杂,包括当中一个矩形的一个顶点和两个顶点在还有一个矩形中的情况。对于本题,则仅仅需考虑上图所看到的的情况就可以,相对照较简单。仅仅需求出总面积。然后减去公共的面积,即为两矩形所形成的面积。
(3)详情见下方代码。希望本文对你有所帮助。
算法代码实现例如以下:
/** * * @author lqq * */ public class Rectangle_Area { public int computeArea(int A, int B, int C, int D, int E, int F, int G,int H) { // // //相离 // if((E>=C || G<=A) && (H<=B || F>=D)){ // int _area1 = (C-A>=0?(C-A):(A-C)) * (B-D>=0?(B-D):(D-B)); // int _area2 = (G-E>=0?(G-D):(D-G)) * (H-F>=0?(H-F):(F-H)); // // return _area1 + _area2; // } // // //包括 // if((A<=E && E<=C && A<=G &&G<=C&&B<=F&&F<=D&&B<=H&&H<=D)){ // int _area1 = (C-A>=0?(C-A):(A-C)) * (B-D>=0?(B-D):(D-B)); // return _area1; // }else if((A>=E && E>=C && A>=G &&G>=C&&B>=F&&F>=D&&B>=H&&H>=D)){ // int _area2 = (G-E>=0?
(G-D):(D-G)) * (H-F>=0?
(H-F):(F-H)); // return _area2; // } // // //相交 分为一个点在里面和两个点在里面 int area = (D - B) * (C - A) + (G - E) * (H - F); // 总面积 int left = Math.max(A, E); int down = Math.max(B, F); int right = Math.min(G, C); int up = Math.min(D, H); if (up <= down || right <= left) { return area; } area = area - (right - left) * (up - down); return area; } }
以上是关于Leetcode_223_Rectangle Area的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 223 Rectangle Area(矩形面积)