zoukankan      html  css  js  c++  java
  • [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.

    Rectangle Area

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

    思路:先判断两个长方形的相交情况,然后计算相交面积,最后计算总共占用面积

    时间复杂度:

    代码:

        public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            return (C-A)*(D-B)+(G-E)*(H-F)-intersectionArea(A, B, C, D, E, F, G, H);
        }
        public int intersectionArea(int A, int B, int C, int D, int E, int F, int G, int H)
        {
            int situation=intersection(A, B, C, D, E, F, G, H);
            if(situation==1)
                return (G-E)*(H-F);
            else if(situation==2)
                return (C-A)*(D-B);
            else if(situation==3)
                return 0;
            else 
                return ((Math.min(H, D)-Math.max(B, F))*(Math.min(C, G)-Math.max(A, E)));
        }
        /**
         * 判断相交情况
         * 1    ABCD包含EFGH
         * 2    EFGH包含ABCD
         * 3    不相交
         * 4    相交   
         * @param A
         * @param B
         * @param C
         * @param D
         * @param E
         * @param F
         * @param G
         * @param H
         * @return
         */
        public int intersection(int A, int B, int C, int D, int E, int F, int G, int H)
        {
            if(D>=H && C>=G && A<=E && B<=F)
                return 1;
            if(G>C && H>D && E<A && F<B)
                return 2;
            //如果两长方形的中心点的连线在x轴上的投影小于两长方形x边长度之和的一半, 并且Y也如此,则这两个长方形相交
            double x1=(A+C)*1.0/2;
            double y1=(B+D)*1.0/2;
            
            double x2=(E+G)*1.0/2;
            double y2=(F+H)*1.0/2;
            
            double rx=(C-A+G-E)*1.0/2;
            double ry=(D-B+H-F)*1.0/2;
            
            if(Math.abs(x2-x1)<rx && Math.abs(y2-y1)<ry)
                return 4;
            else
            {
                return 3;
            }
        }

    优化:

    扩展;

  • 相关阅读:
    CSS
    人物
    CSS
    CSS
    概念- 工业4.0
    C#正则表达式
    六月定律
    c#中实现登陆窗口(无需隐藏)
    c#中关于String、string,Object、object,Int32、int
    一个快速找第k+1小的算法
  • 原文地址:https://www.cnblogs.com/maydow/p/4641335.html
Copyright © 2011-2022 走看看