-
Notifications
You must be signed in to change notification settings - Fork 0
/
M 223. Rectangle Area
101 lines (73 loc) · 3.34 KB
/
M 223. Rectangle Area
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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:
-10^4 <= ax1 <= ax2 <= 10^4
-10^4 <= ay1 <= ay2 <= 10^4
-10^4 <= bx1 <= bx2 <= 10^4
-10^4 <= by1 <= by2 <= 10^4
题目翻译:
在二维平面上给定两个矩形的坐标,返回两个矩形覆盖的总面积。
第一个矩形由其左下角(ax1, ay1)和右上角(ax2, ay2)定义。
第二个矩形由其左下角(bx1, by1)和右上角(bx2, by2)定义。
示例 1:
矩形面积
输入:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
输出:45
示例 2:
输入:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
输出:16
约束:
-10^4 <= ax1 <= ax2 <= 10^4
-10^4 <= ay1 <= ay2 <= 10^4
-10^4 <= bx1 <= bx2 <= 10^4
-10^4 <= by1 <= by2 <= 10^4
class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
// 计算两个矩形的总面积
int totalArea = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1);
// 计算重叠矩形的边界坐标
int overlapLeft = Math.max(ax1, bx1);
int overlapBottom = Math.max(ay1, by1);
int overlapRight = Math.min(ax2, bx2);
int overlapTop = Math.min(ay2, by2);
// 如果矩形重叠
if (overlapLeft < overlapRight && overlapBottom < overlapTop) {
// 减去重叠部分的面积
totalArea -= (overlapRight - overlapLeft) * (overlapTop - overlapBottom);
}
// 返回总面积
return totalArea;
}
}
best answer
class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
// 计算矩形1的面积
long A1 = (ax2 - ax1) * (ay2 - ay1);
// 计算矩形2的面积
long A2 = (bx2 - bx1) * (by2 - by1);
// 计算重叠部分的x轴边界
int x1 = Math.max(ax1, bx1);
int x2 = Math.min(ax2, bx2);
// 如果x轴边界不重叠,则直接返回两个矩形的面积之和
if (x2 <= x1) return (int) (A1 + A2);
// 计算重叠部分的y轴边界
int y1 = Math.max(ay1, by1);
int y2 = Math.min(ay2, by2);
// 如果y轴边界不重叠,则直接返回两个矩形的面积之和
if (y2 <= y1) return (int) (A1 + A2);
// 计算重叠部分的面积
long A3 = (x2 - x1) * (y2 - y1);
// 返回两个矩形的面积之和减去重叠部分的面积
return (int) (A1 + A2 - A3);
}
}
从算法的层面讲,这道题的解法是先分别计算两个矩形的面积,然后计算x轴和y轴的重叠边界。如果某个轴上没有重叠,则说明两个矩形不重叠,直接返回两个矩形的面积之和。否则,计算重叠部分的面积,并从两个矩形的面积之和中减去重叠部分的面积,得到最终的覆盖总面积。