卖萌的弱渣

I am stupid, I am hungry.

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 Assume that the total area is never beyond the maximum possible value of int.

Solution

  • 面积=两个长方形面积-相交部分的面积
(Rectangle-Area.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
        """
        # 两个长方形面积和
        area = (C-A)*(D-B) + (G-E)*(H-F)

        if A > G or C < E or D < F or B > H:
            return area
        else:
            return area - (min(D,H)-max(B,F)) * (min(C,G) - max(A,E))

  • Java:
(Rectangle-Area.java) download
1
2
3
4
5
6
7
8
9
public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area = (G-E)*(H-F) + (C-A)*(D-B);
        if (A>G || B>H || D<F || C<E)
            return area;
        else
            return area-(Math.min(C,G)-Math.max(A,E))*(Math.min(D,H)-Math.max(B,F));
    }
}