My easy c++ solution


  • 17
    R
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) 
    {
        int total = (C-A) * (D-B) + (G-E) * (H-F);
        
        if (C<=E || A>=G || B>=H || D<=F )
            return total;
        else
        {
            vector <int> h;
            h.push_back(A);
            h.push_back(C);
            h.push_back(E);
            h.push_back(G);
       
            vector <int> v;
            v.push_back(B);
            v.push_back(D);
            v.push_back(F);
            v.push_back(H);
        
            sort(h.begin(), h.end());
            sort(v.begin(), v.end());
        
            total = total - (h[2] - h [1]) * (v[2] - v[1]);
            return total;
        }
    }

  • 0
    Z

    you don't need abs() when calculating total I think


  • 0
    R

    Hi zxl9171, thanks for your comments. Yes, I have updated my code accordingly.


  • 0
    P

    so clever!!!! very brilliant idea!


  • 0
    L

    This is beautiful!


  • 0
    S

    your method is so clean and beautiful~!

    but the sorting part slow down a little bit.

        int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) 
        {
            int temp,total = (C-A) * (D-B) + (G-E) * (H-F);
            if (C<=E || A>=G || B>=H || D<=F )
                return total;
            else
            {
                if(A>C)
                {
                    temp=A;
                    A=C;
                    C=temp;
                }
                if(E>G)
                {
                    temp=E;
                    E=G;
                    G=temp;
                }
                if(B>D)
                {
                    temp=B;
                    B=D;
                    D=temp;
                }
                if(F>H)
                {
                    temp=F;
                    F=H;
                    H=temp;
                }
                total = total - ( min(C,G) - max(A,E))*(min(D,H)- max(B,F));
                return total;
            }
        }

Log in to reply
 

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