AC Python solution 5 lines with no if else


  • 0
    def computeArea(self, x1, y1, x2, y2, x3, y3, x4, y4):
        wt, wa, wb = max(x2, x4) - min(x1, x3), x2 - x1, x4 - x3
        ws = max(0, wa + wb - wt)
        ht, ha, hb = max(y2, y4) - min(y1, y3), y2 - y1, y4 - y3
        hs = max(0, ha + hb - ht)
        return wa * ha + wb * hb - ws * hs
    
    
    # 3081 / 3081 test cases passed.
    # Status: Accepted
    # Runtime: 120 ms
    

    Use min max to define width/height of total rectangle, rectangle A, rectangle B and overlapping rectangle (we can call it shadow part) to avoid explicit if else statements.

    Same idea, another implement

    def computeArea(self, x1, y1, x2, y2, x3, y3, x4, y4):
        a = [x2 - x1, y2 - y1]
        b = [x4 - x3, y4 - y3]
        total = [max(x2, x4) - min(x1, x3), max(y2, y4) - min(y1, y3)]
        shadow = [max(0, a[0] + b[0] - total[0]), max(0, a[1] + b[1] - total[1])]
        return a[0] * a[1] + b[0] * b[1] - shadow[0] * shadow[1]
    
    
    # 3081 / 3081 test cases passed.
    # Status: Accepted
    # Runtime: 120 ms

Log in to reply
 

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