Wednesday, January 11, 2017

Rectangle Overlap

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.

/*
There are eight conditions totally. 
time:O(1), space:O(1)
*/
public class Solution {
    public int computeArea(int A, int B, int C, int D, 
                           int E, int F, int G, int H) {
        int l = Math.max(A, E);
        int r = Math.max(l, Math.min(C, G));
        int b = Math.max(B, F);
        int t = Math.max(b, Math.min(D, H));
        return (C - A) * (D - B) + 
               (G - E) * (H - F) - 
               (r - l) * (t - b) ;
    }
}

No comments:

Post a Comment