Just another short way


  • 201
    M

    Instead of checking whether the rectangles overlap, I max right with left (and top with bottom). Haven't seen that in other solutions.

    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int left = max(A,E), right = max(min(C,G), left);
        int bottom = max(B,F), top = max(min(D,H), bottom);
        return (C-A)*(D-B) - (right-left)*(top-bottom) + (G-E)*(H-F);
    }

  • 1
    C

    Great solution! This method does not need to check if two rectangles overlap since the overlapping area will be zero if overlapping does not exist.


  • 29
    A

    x canot be just min -max because of the int limit

    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H)
    {
        int x = min(G, C) > max(E, A) ? (min(G, C) - max(E, A)) : 0;
        int y = min(D, H) > max(B, F) ? (min(D, H) - max(B, F)) : 0;
        return (D - B) * (C - A) + (G - E) * (H - F) - x * y;
    }
    

  • 1

    Great answer. This will prevent overflow.


  • 0

    yea i did the same sol, this Q reminds me of elementary school math olympic...


  • 0
    F
    class Solution {
    public:
        int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            long long LA = A, LB = B, LC = C, LD = D, LE = E, LF = F, LG = G, LH = H;
            return (LD - LB) * (LC - LA) + (LG - LE) * (LH - LF) -
                   max(0ll, (min(LC, LG) - max(LA, LE))) * max(0ll, (min(LD, LH) - max(LB, LF)));
        }
    };

  • 1

    Very neat solution! Really bad at this kinda problem. Thanks for sharing!


  • 0

    @ManuelP Brillliant.............


  • 1
    J
    public int ComputeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    
        int abcd = (A-C)*(B-D);
        int efgh = (E-G)*(F-H);
        
        int common = OverlapLength(A, C, E, G) * OverlapLength(B, D, F, H);
            
        return abcd + efgh - common;
    }
    
    
    /*
        ACEG => 0
        ACEG => CE
        AECG => EC
        EACG => AC
        EAGC => AG
        EGAC => 0
    */
    private int OverlapLength(int A, int C, int E, int G)
    {
        if(C < E || A > G)
            return 0;
        return Math.Min(C, G) - Math.Max(A, E);
    }

  • 0
    Y
        public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            return (C-A)*(D-B)+(G-E)*(H-F)-(int)(Math.max(0,((long)Math.min(C,G)-(long)Math.max(A,E)))*Math.max(0,((long)Math.min(D,H)-(long)Math.max(B,F))));
        }
    

  • 2

    @yangleizou
    You are making your logic unreadable.
    Shorter does not always mean good and writing everything in one line does not equal to shorter.


  • 0
    L

    This is a smart solution based on a observation.


  • 0
    A

    Brilliant solution!
    Very neat. Thanks


  • 0
    A

    @ManuelP clean solution


Log in to reply
 

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