边工作边刷题:70天一遍leetcode: day 67-1

Rectangle Area

要点:基本思路就是先分开算再减去相交部分,这题的难点是如何检查是否相交和如何算出相交部分的面积。

  • 2d转化为1d:x轴和y轴是orthogonal的。可以分开考虑。这样检查不相交很简单,4个or条件。注意x/y轴只要一个不相交就完全没交集
  • 相交部分如何算?还是x/y轴分开,以x轴为例,intuition为相交部分还是左右边作为左右边计算面积。所以相交部分为左边最大和右边最小(同理,y轴为上边最小和下边最大)。其实检查部分也可以依据这个计算省2个条件

这题如果直接通过A/B/C/D记公式去搞明白几乎不可能。以上面的描述来记会容易些。

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
        """
        sumArea = (D-B)*(C-A)+(H-F)*(G-E)
        if (H<B or D<F) or (A>G or E>C):
            return sumArea
        return sumArea-(min(C,G)-max(A,E))*(min(H,D)-max(F,B))
posted @ 2016-06-05 05:29  absolute100  阅读(113)  评论(0编辑  收藏  举报