Rectangle Area
Problem: Rectangle Area
We need to calculate areas of two rectangles, add them up and subtract the overlapping area. In my solution, I assume E may be left to A or something like that and do a lot of dirty works, kind of situations not in test cases. Another faster solution fits test cases better while it's not a universal one.
Code in Python:
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
width1, height1 = (A, C), (B, D)
width2, height2 = (E, G), (F, H)
width0, height0 = self.intersect(width1, width2), self.intersect(height1, height2)
return (width1[1]-width1[0])*(height1[1]-height1[0])+(width2[1]-width2[0])*(height2[1]-height2[0])-(width0[1]-width0[0])*(height0[1]-height0[0])
def intersect(self, interval1, interval2):
if interval1[0] > interval2[0]: interval1, interval2 = interval2, interval1
if interval1[1] <= interval2[0]: return (0, 0)
elif interval2[0] <= interval1[1] and interval1[1] <= interval2[1]: return (interval2[0], interval1[1])
else: return (interval2[0], interval2[1])