[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:
Rectangle Area
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 |
|
相关题目
1 |
|