My one line solution in Python


  • 0
    H

    First I got a straightforward solution. If there is no intersection in two rectangles, just return the sum area of the rectangles;Else you should minus the intersection area,

    def computeArea(self, A, B, C, D, E, F, G, H):
        if C < E or G < A or D < F or H < B:
            return (C-A)*(D-B) + (H-F)*(G-E)
        lst = []
        lst.append(A)
        lst.append(C)
        lst.append(E)
        lst.append(G)
        lst.sort()
        w = lst[2]-lst[1]
        lst = []
        lst.append(B)
        lst.append(D)
        lst.append(F)
        lst.append(H)
        lst.sort()
        h = lst[2] - lst[1]
        return (C-A)*(D-B) + (H-F)*(G-E) - w*h  
    

    Then I optimize it to just one line, since we can get the second and third largest width or height use the min and max.

    def computeArea(self, A, B, C, D, E, F, G, H):
        return (C-A)*(D-B) + (H-F)*(G-E) if C < E or G < A or D < F or H < B else (C-A)*(D-B) + (H-F)*(G-E) - (min(C,G)-max(A,E))*(min(D,H)-max(B,F))

Log in to reply
 

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