Easy and concise solution in JAVA with explanation


  • 0
    S

    total area=area1+area2-overlaparea
    ->So we need to calculate overlap area->calcuate the boundary coordinate of overlap area.

    So,I listed several overlap cases and tried to use conditional sentences to define area of each case.(How stupid I was ==

    But after observation,I noticed the boundary of all cases has same properties:
    1.the area's left is the rightmost of the left of the two rectangles.->Math.max(A,E)
    2.the area's right is the leftmost of the right of the two rectangles.->Math.min(C,G)
    3.the area's top is the bottommost of the top of the two rectangles.->Math.min(D,H)
    4.the area's bottom is the topmost of the bottom of the two rectangles.->Math.max(B,F)

    But how to represent the case which didn't overlap? If there is no overlap,right<=left or bottom<=top or both ->using quick return when test them.

    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            int sum=(C-A)*(D-B)+(G-E)*(H-F);
            int areaLeft=Math.max(A,E);
            int areaRight=Math.min(C,G);
            if(areaRight<=areaLeft){
                return sum;
            }
            int areaBottom=Math.max(B,F);
            int areaTop=Math.min(D,H);
            if(areaBottom>=areaTop){
                return sum;
            }
            return sum-(areaRight-areaLeft)*(areaTop-areaBottom);
        }
    

Log in to reply
 

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