LeetCode Rectangle Area

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.

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

方法

通过方法:两个矩阵的面积-共有面积 = 两个矩阵的面积

观察图可知重叠矩阵左下角的点为(Math.max(A,E),Math.max(B,F)),右上角的点为(Math.min(C,G),Math.min(D,H)),即可求得重叠矩阵的共有面积。

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int s1 = (C-A)*(D-B);
        int s2 = (G-E)*(H-F);

        int leftX = Math.max(A,E);
        int leftY = Math.max(B,F);
        int rightX = Math.min(C,G);
        int rightY = Math.min(D,H);

        int overlap = 0;
        if(rightX > leftX && rightY > leftY){
            overlap = (rightX-leftX)*(rightY-leftY);
        }
        return s1+s2-overlap;
    }
}
Share