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.
rec

分析


最重要的的是找到两个长方形的相交面积的表达式,画个草图就理解了,所以说,编程还是得数学好。需要注意的一点是,在判断中,应该直接做判断,比如if(l2 > l1 && h2 > h1),而不是if(l2-l1 > 0 && h2-h1>0),因为这样有可能溢出(这个bug让我折腾好久),这个边界情况应该注意,今后写代码也是如此。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int l1 = max(A, E);
int l2 = min(C, G);

int h1 = max(B, F);
int h2 = min(D, H);
int extra_area = 0;

if(l2 > l1 && h2 > h1) {
extra_area = (l2-l1) * (h2-h1);
}else {
extra_area = 0;
}

return (G-E)*(H-F)+(C-A)*(D-B)-extra_area;
}
};

解决方案2(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {

int l1 = Math.max(A, E);
int l2 = Math.min(C, G);

int h1 = Math.max(B, F);
int h2 = Math.min(D, H);
int extra_area = 0;

if(l2 > l1 && h2 > h1) {
extra_area = (l2-l1)*(h2-h1);
}else {
extra_area = 0;
}

return (G-E)*(H-F)+(C-A)*(D-B)-extra_area;
}
}

解决方案3(Python)


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
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
l1 = max(A, E)
l2 = min(C, G)

h1 = max(B, F)
h2 = min(D, H)
extra_area = 0

if(l2 > l1 and h2 > h1):
extra_area = (l2-l1) * (h2-h1)
else:
extra_area = 0

return (G-E)*(H-F)+(C-A)*(D-B)-extra_area

题目来源