zoukankan      html  css  js  c++  java
  • LeetCode#223 Rectangle Area

    Problem Definition:

    Find the total area covered by two rectilinear rectangles in a 2D plane.

    Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

    Rectangle Area

    Assume that the total area is never beyond the maximum possible value of int.

    Solution:

    水平方向有三种情况:

    1)  A-------------C    

                E--------------G

      或

      E--------------G

                                      A-------------C

      条件:E>G||A>G

    2)A--------------C

        E-----G

      或

      E-------------------G

        A-----------C

      条件:((C>G) &&(E>A))  ||  ((G>C)&&(A>E))

    3)A-------------C

            E--------------G

      或

      E--------------G

          A-------------C

      条件:余下的情况

    垂直方向同理。

    代码:

     1 def computeArea(self, A, B, C, D, E, F, G, H):
     2         if E>=C or A>=G or F>=D or B>=H:
     3             return (C-A)*(D-B)+(G-E)*(H-F)
     4         if C>G and E>A:
     5             a=G-E
     6         elif G>C and A>E:
     7             a=C-A
     8         else:
     9             a=min(G-A,C-E)
    10         if D>H and F>B:
    11             b=H-F
    12         elif H>D and B>F:
    13             b=D-B
    14         else:
    15             b=min(H-B,D-F)
    16         dup=a*b
    17         return (C-A)*(D-B)+(G-E)*(H-F)-dup

    一种更简便的方法:

    1 def computeArea(self, A, B, C, D, E, F, G, H):
    2         areaA = (C - A) * (D - B)
    3         areaB = (G - E) * (H - F)
    4         l = max(0, min(C, G) - max(A, E))
    5         h = max(0, min(D, H) - max(B, F))
    6         return areaA + areaB - l * h
  • 相关阅读:
    二进制运算基础
    初识Tomcat系统架构
    MySQL InnoDB引擎锁的总结
    Java并发编程:并发容器之CopyOnWriteArrayList
    java类的加载机制
    Nginx实现tomcat集群进行负载均衡
    Java序列化对象为字符串并将字符串反序列化为对象
    数据库的四大特性及事务的隔离级别
    人性的弱点
    华为工作法摘抄笔记
  • 原文地址:https://www.cnblogs.com/acetseng/p/4651811.html
Copyright © 2011-2022 走看看