• Leetcode 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.

     

    Assume that the total area is never beyond the maximum possible value of 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)

    注意: min(C, G) - max(A, E), min(D, H) - max(B, F)可能会溢出, 需要先转换成long 判断后再转换回int.


     Java code:

     1  public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
     2         int sums = (C-A) *(D-B) + (G-E)*(H-F);
     3         long x = (long)Math.min(C,G)- (long)Math.max(A,E);
     4         long y = (long)Math.min(D,H)- (long)Math.max(B,F);
     5         if(x <  Integer.MIN_VALUE || x > Integer.MAX_VALUE) { x = 0;}
     6         if(y <  Integer.MIN_VALUE || y > Integer.MAX_VALUE) { y = 0;}
     7         int m = (int)x;
     8         int n = (int)y;
     9        return  sums - Math.max(m, 0) * Math.max(n, 0);
    10     }

    Reference:

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

  • 相关阅读:
    hdu 1754 I Hate It(线段树水题)
    hdu 1166敌兵布阵(线段树入门题)
    多校1007 Naive Operations
    51NOD 1277 字符串中的最大值(KMP)
    括号匹配
    Visual Studio中定义OVERFLOW不能用
    数据结构第二章小节
    关键字new与malloc函数
    构造函数不能为虚/重载函数总结
    预处理之宏定义
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4793469.html
Copyright © 2020-2023  润新知