LeetCode: 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

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Note:

Assume that the total area is never beyond the maximum possible value of int.
*/
class RectanlgeArea {
    public int computeArea(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
        int left = Math.max(x1, x3);
        int right= Math.min(x2, x4);
        int top = Math.min(y2, y4);
        int bottom = Math.max(y1, y3);
        int r1Area = Math.abs(x2-x1)*Math.abs(y2-y1);
        int r2Area = Math.abs(x3-x4)*Math.abs(y3-y4);
        int overlapArea = 0;
        if(right>left && top>bottom)
            overlapArea = Math.abs(right-left)*Math.abs(top-bottom);
        return r1Area + r2Area - overlapArea;
    }
}

No comments:

Post a Comment