C++ solution with explanation


  • 2
    R

    class Solution {
    public:
    int RectArea(int left, int bottom, int right, int top){

        int result = (right > left && top > bottom)? ((right-left) * (top-bottom)) : 0; // If there is no common area it will be 0;
        return result;
    }
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { // For better understanding the problem try to draw intersected/not intersected rectangles;
        int left1 = A;
        int bottom1 = B;
        int right1 = C;
        int top1 = D;
        int left2 = E;
        int bottom2 = F;
        int right2 = G;
        int top2 = H;
        int interleft = max(left1, left2);          //IF two rectangle intersects max will return the intersect point X value; 
        int interright = min(right1, right2);       //IF two rectangle intersects min will return the intersect point X value
        int intertop = min(top1, top2);             //IF two rectangle intersects min will return the intersect point Y value
        int interbottom = max(bottom1, bottom2);    //IF two rectangle intersects max will return the intersect point Y value
        int total_area = RectArea(left1, bottom1, right1, top1) + RectArea(left2, bottom2, right2, top2) - RectArea(interleft, interbottom, interright, intertop);
        return total_area;
    }
    

    };


Log in to reply
 

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