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

    Problem:

    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.

    Analysis:

    The seems complex problem could be easily analyzed and sovled through simple analysis. 
    If you try to analyze and distinguish in the scope of rectangle, it is too crazy to clear the relationship between them. 
    
    But we could actually do it in a very simple way. We analyze the prolem through two separate direction: vertical direction and horizontal direction.
    Principle: Once rectangle A in connected rectangle B, there must be a overlay either in vertical direction or horizontal direction. Otherwise they could not overlay with each other. 
    
    The horizontal direction:
    A-------------------- C
    
            E--------------------------G
            
            
    E-------------------- G
            A------------------------C
    
    If the two rectangles overlay with each other, at horizontal direction, it must meet one the above situation.
    If not, they are not overlay.
            if (A > G || C < E)
                return (H-F)*(G-E) + (D-B)*(C-A);
    
    We could also see that, since A is the left edge of C, E is the left edge of G,
    The left coordinate for the overlaied rectangles is :
    ---------------------------------------------------
    int left = Math.max(A, E);
    The right coordinate for the overlaied rectangles is :
    -------------------------------------------------------
    int right = Math.min(C, G);
    
    The same analysis could apply to the vertical direction.
    
    Skill:
    To compute the overall area, we could use: total area - overlaid area.

    Solution:

    public class Solution {
        public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            if (A > G || C < E)
                return (H-F)*(G-E) + (D-B)*(C-A);
            if (B > H || D < F)
                return (H-F)*(G-E) + (D-B)*(C-A);
            int left = Math.max(A, E);
            int right = Math.min(C, G);
            int bottom = Math.max(B, F);
            int top = Math.min(D, H);
            return (H-F)*(G-E) + (D-B)*(C-A) - (top-bottom)*(right-left);
        }
    }
  • 相关阅读:
    QT 创建一个线程播放监控视频
    C++基础(静态数据成员和静态成员函数)
    SDK的使用步骤
    QT加载自带字体
    QT release版QAudioDeviceInfo获取不到音频设备,而debug版可以获取到
    通过vs2015给QT添加模块
    pycharm修改字体与主题
    日志学习(二)——日志处理封装
    日志学习(一)
    配置文件学习(二)--写入配置文件
  • 原文地址:https://www.cnblogs.com/airwindow/p/4768348.html
Copyright © 2011-2022 走看看