Tuesday, September 1, 2015

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
Assume that the total area is never beyond the maximum possible value of int.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
Understand the problem:
The returned area = area A + area B - overlapped area. 

Code (Java):
public class Solution {
    private class Interval {
        public int start;
        public int end;
        
        public Interval(int s, int e) {
            this.start = s;
            this.end = e;
        }
    }
    
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        Interval x1 = new Interval(A, C);
        Interval y1 = new Interval(B, D);
        
        Interval x2 = new Interval(E, G);
        Interval y2 = new Interval(F, H);
        
        int x3 = 0;
        int y3 = 0;
        
        if (x1.start <= x2.start) {
            if (x1.end > x2.start) {
                x3 = Math.min(x1.end, x2.end) - Math.max(x1.start, x2.start);
            }
        } else {
            if (x1.start < x2.end) {
                x3 = Math.min(x1.end, x2.end) - Math.max(x1.start, x2.start);
            }
        }
        
        if (y1.start < y2.start) {
            if (y1.end > y2.start) {
                y3 = Math.min(y1.end, y2.end) - Math.max(y1.start, y2.start);
            }
        } else {
            if (y1.start < y2.end) {
                y3 = Math.min(y1.end, y2.end) - Math.max(y1.start, y2.start);
            }
        }
        
        int overlappedArea = x3 * y3;
        
        int area1 = (x1.end - x1.start) * (y1.end - y1.start);
        int area2 = (x2.end - x2.start) * (y2.end - y2.start);
        
        return area1 + area2 - overlappedArea;
    }
}

A neat code:
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    if(C<E||G<A )
        return (G-E)*(H-F) + (C-A)*(D-B);
 
    if(D<F || H<B)
        return (G-E)*(H-F) + (C-A)*(D-B);
 
    int right = Math.min(C,G);
    int left = Math.max(A,E);
    int top = Math.min(H,D);
    int bottom = Math.max(F,B);
 
    return (G-E)*(H-F) + (C-A)*(D-B) - (right-left)*(top-bottom);
}

No comments:

Post a Comment