• *Rectangle Area


    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.

    [LeetCode]Rectangle Area

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

    题目大意:

    计算二维平面上两个直线矩形的覆盖面积。

    矩形通过其左下角和右上角的坐标进行定义。

    假设总面积不会超过int的最大值。

    解题思路:

    简单计算几何。根据容斥原理:S(M ∪ N) = S(M) + S(N) - S(M ∩ N)

    题目可以转化为计算矩形相交部分的面积

    S(M) = (C - A) * (D - B)

    S(N) = (G - E) * (H - F)

    S(M ∩ N) = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0)

     If they do not have overlap, the total area is the sum of 2 rectangle areas. If they have overlap, the total area should minus the overlap area.

     1 public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
     2     if(C<E||G<A )
     3         return (G-E)*(H-F) + (C-A)*(D-B);
     4  
     5     if(D<F || H<B)
     6         return (G-E)*(H-F) + (C-A)*(D-B);
     7  
     8     int right = Math.min(C,G);
     9     int left = Math.max(A,E);
    10     int top = Math.min(H,D);
    11     int bottom = Math.max(F,B);
    12  
    13     return (G-E)*(H-F) + (C-A)*(D-B) - (right-left)*(top-bottom);
    14 }

    reference: http://www.programcreek.com/2014/06/leetcode-rectangle-area-java/

    http://bookshadow.com/weblog/2015/06/08/leetcode-rectangle-area/

  • 相关阅读:
    数据结构之队列
    设计模式之策略模式的使用
    搭建一个高可用的redis环境
    Linux遗忘命令
    重温几种排序算法之希尔排序、归并排序、快速排序
    HashMap的简单实现
    Java GC基础
    2016年年终总结
    Shell 备忘录
    Openstack Grizzily 单节点测试机安装( All In One CentOS/RHEL)
  • 原文地址:https://www.cnblogs.com/hygeia/p/4777557.html
Copyright © 2020-2023  润新知