1. 程式人生 > >LeetCode 223. Rectangle Area(兩個矩形的複合面積計算)

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.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.

思路:兩個矩形各自的面積之和,減去重疊部分的面積,所以難點是如何計算重疊部分的面積。可以對兩個矩形的左邊、下邊、右邊、上邊各自比較,例如兩個矩形的左邊比較,取最大者;兩個矩形的右邊比較,取最小者,兩個矩形的下邊比較,取最大者;兩個矩形的上邊比較,取最小者。


程式碼:

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int sum = (C-A)*(D-B)+(G-E)*(H-F);
        if (A<E) A=E;
        else if (E<A) E=A;
        if (A>=C || E>=G) return sum;
        if (G>C) G=C;
        else if (C>G) C=G;
        if (A>=C || E>=G) return sum;
        if (B<F) B=F;
        else if (F<B) F=B;
        if (B>=D || F>=H) return sum;
        if (D>H) D=H;
        else if (H>D) H=D;
        if (B>=D || F>=H) return sum;
        return sum-(C-A)*(D-B);
    }
}
可以對上面程式碼進行簡化:
public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        return (int)((C-A)*(D-B)+(G-E)*(H-F)-Math.max(0, (long)Math.min(C,G)-Math.max(A,E))*Math.max(0,(long)Math.min(D,H)-Math.max(B,F)));
    }
}