My Object Oriented Solution


  • 0
    T
    class Point {
        int x;
        int y;
        Point (int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    
    class Rectangle {
        Point bottomLeft;
        Point topRight;
        
        Rectangle (Point bottomLeft, Point topRight) {
            this.bottomLeft = bottomLeft;
            this.topRight = topRight;
        }
        
        Rectangle (int A, int B, int C, int D) {
            this(new Point(A, B), new Point(C, D));
        }
        
        // calculate area
        public int getArea() {
            return Math.abs(topRight.x - bottomLeft.x) * 
                Math.abs(topRight.y - bottomLeft.y);
        }
        
        // return a rectange which is the common area between this rectangle and the given rectangle;
        // otherwise, a rect with area of 0 will be returned
        public Rectangle getOverlayRect(Rectangle rect) {
            int A = Math.max(bottomLeft.x, rect.bottomLeft.x);
            int B = Math.max(bottomLeft.y, rect.bottomLeft.y);
            int C = Math.min(topRight.x, rect.topRight.x);
            int D = Math.min(topRight.y, rect.topRight.y);
            
            if (A > C || B > D) {
                // rectangles did not overlay
                return new Rectangle(0, 0, 0, 0);
            }
            return new Rectangle(A, B, C, D);
        }
    }
    
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        Rectangle rect1 = new Rectangle(A, B, C, D);
        Rectangle rect2 = new Rectangle(E, F, G, H);
        Rectangle overlaidRect = rect1.getOverlayRect(rect2);
        return rect1.getArea() + rect2.getArea() - overlaidRect.getArea();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.