C++ 18ms solution


  • 0
    class Solution {
    public:
        int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            //Overlap Rectangle:Bottom_left (a,b),Top_right(c,d)
            int a,b,c,d;
           
            //Every first 'if' below means the two Rect are not overlap, return the sum of area immediately.
            //compute a
            if(C<E||A>G) return (D-B)*(C-A)+(H-F)*(G-E); 
            else if(A<E) a=E;
            else a=A;
            
            //compute b
            if(B>H||D<F) return (D-B)*(C-A)+(H-F)*(G-E);
            else if(B>F) b=B;
            else b=F;
            
            //compute c
            if(C<E||A>G) return (D-B)*(C-A)+(H-F)*(G-E);
            else if(C<G) c=C;
            else c=G;
            
            //compute d
            if(B>H||D<F) return (D-B)*(C-A)+(H-F)*(G-E);
            else if(D<H) d=D;
            else d=H;
            
            //Overlap area
            int overlap=(d-b)*(c-a);
            
            //Rectangle Area = Area ( RectangleA + RectangleB - Overlap)
            return (D-B)*(C-A)+(H-F)*(G-E)-overlap;
        
        }
    };
    

Log in to reply
 

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