其他分享
首页 > 其他分享> > [LeetCode] 223. Rectangle Area

[LeetCode] 223. 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

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Note:

Assume that the total area is never beyond the maximum possible value of int.

矩形面积。题意是给两个矩形的左下角的坐标和右上角的坐标,请你返回由这两个矩形组成的多边形的面积。

思路是先计算两个矩形各自的面积,再计算两者重叠的部分,最后用两个矩形各自的面积 - 两者重叠的部分即可。各自计算两个长方形的面积这个很好处理,但是如何计算重叠部分的面积呢?这个题不要想复杂了,可以就参照题目给的例子来计算重叠部分的面积。对于这个重叠的部分,左下角的横坐标是A和E的较大值,右上角的横坐标是C和G的较小值,所以重叠部分的长是Math.min(C, G) - Math.max(A, E)。同理,重叠部分的高 = Math.min(D, H) - Math.max(B, F)。

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
 3         int areaA = (C - A) * (D - B);
 4         int areaB = (G - E) * (H - F);
 5         int left = Math.max(A, E);
 6         int right = Math.min(C, G);
 7         int top = Math.min(D, H);
 8         int bottom = Math.max(B, F);
 9 
10         int overlap = 0;
11         if (right > left && top > bottom) {
12             overlap = (right - left) * (top - bottom);
13         }
14         return areaA + areaB - overlap;
15     }
16 }

 

JavaScript实现

 1 /**
 2  * @param {number} A
 3  * @param {number} B
 4  * @param {number} C
 5  * @param {number} D
 6  * @param {number} E
 7  * @param {number} F
 8  * @param {number} G
 9  * @param {number} H
10  * @return {number}
11  */
12 var computeArea = function (A, B, C, D, E, F, G, H) {
13     let areaA = (C - A) * (D - B);
14     let areaB = (G - E) * (H - F);
15     let left = Math.max(A, E);
16     let right = Math.min(C, G);
17     let top = Math.min(D, H);
18     let bottom = Math.max(B, F);
19 
20     let overlap = 0;
21     if (right > left && top > bottom) {
22         overlap = (right - left) * (top - bottom);
23     }
24     return areaA + areaB - overlap;
25 };

 

LeetCode 题目总结

标签:right,bottom,int,number,param,Rectangle,223,LeetCode,Math
来源: https://www.cnblogs.com/cnoodle/p/13624661.html