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;
            }
        }

    优化:

    扩展;

  • 相关阅读:
    IOS:接口返回包含转义字符去掉转义字符
    properties和yml进行对比
    IDEA安装插件时搜索不到,一直在转圈刷新,无法安装
    VMware 15 虚拟机黑屏问题
    扩容根分区
    CentOS 6 各种启动文件损坏及修复
    RabbitMQ面试题
    FTP,SFTP服务器登录权限和根目录的设置
    Tee命令的几个使用实例
    ssh-copy-id 后无法免密登录
  • 原文地址:https://www.cnblogs.com/maydow/p/4641335.html
Copyright © 2011-2022 走看看