[LeetCode] 223. Rectangle Area
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
The first rectangle is defined by its bottom-left corner (ax1, ay1)
and its top-right corner (ax2, ay2)
.
The second rectangle is defined by its bottom-left corner (bx1, by1)
and its top-right corner (bx2, by2)
.
Example 1:
Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 Output: 45
Example 2:
Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 Output: 16
Constraints:
-104 <= ax1 <= ax2 <= 104
-104 <= ay1 <= ay2 <= 104
-104 <= bx1 <= bx2 <= 104
-104 <= by1 <= by2 <= 104
矩形面积。
给你 二维 平面上两个 由直线构成且边与坐标轴平行/垂直 的矩形,请你计算并返回两个矩形覆盖的总面积。
每个矩形由其 左下 顶点和 右上 顶点坐标表示:
第一个矩形由其左下顶点 (ax1, ay1) 和右上顶点 (ax2, ay2) 定义。
第二个矩形由其左下顶点 (bx1, by1) 和右上顶点 (bx2, by2) 定义。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rectangle-area
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意是给两个矩形的左下角的坐标和右上角的坐标,请你返回由这两个矩形组成的多边形的面积。
思路是先计算两个矩形各自的面积,再计算两者重叠的部分,最后用两个矩形各自的面积 - 两者重叠的部分即可。各自计算两个长方形的面积这个很好处理,但是如何计算重叠部分的面积呢?这个题不要想复杂了,可以就参照题目给的例子来计算重叠部分的面积。对于这个重叠的部分,左下角的横坐标是A和E的较大值,右上角的横坐标是C和G的较小值,所以重叠部分的长是Math.min(ax2, bx2) - Math.max(ax1, bx1)。同理,重叠部分的高 = Math.min(ay2, by2) - Math.max(ay1, by1)。
时间O(1)
空间O(1)
Java实现
1 class Solution { 2 public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { 3 int areaA = (ax2 - ax1) * (ay2 - ay1); 4 int areaB = (bx2 - bx1) * (by2 - by1); 5 int left = Math.max(ax1, bx1); 6 int right = Math.min(ax2, bx2); 7 int top = Math.min(ay2, by2); 8 int bottom = Math.max(ay1, by1); 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 };
相关题目
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步