• LeetCode -- Rectangle Area


    Question:

    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:

    问题描述:计算在二维坐标系中两个矩阵覆盖的面积。每个矩阵由它的左下角和右上角的坐标表示。

    思路:关键是求两个矩阵的相交部分的面积。有3种情况:一种是无相交的部分;一种是只有横向和纵向的相交部分,一种是横向和纵向都有相交部分。然而,由图形可知,(A,B)的坐标一定是小于(C,D),(E,F)的坐标一定小于(G,H)。因此看有无相交时,只需要取两个矩形中左下角中较大的作为新矩形的左下角坐标和右上角中较小的作为新矩形的右上角坐标,若新的矩形中右上角的坐标还要比左下角的坐标小,则说明原来的两个矩形不相交,反之则相交。

    PS:在计算矩阵面积的过程中,注意int型坐标的计算是否会越界。

    Answer:

    public class Solution {
        public static int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            int t1 = Math.max(A, E), t2 = Math.max(B, F), t3 = Math.min(C, G), t4 = Math.min(D, H);
            int area1 = getArea(A, B, C, D);
            int area2 = getArea(E, F, G, H);
            int area3 = getArea(t1, t2, t3, t4);
            if(t1 > t3 || t2 > t4)
                return area1 + area2;
            else 
                return area1 + area2 - area3;
            
                
        }
        
        public static int getArea(int A, int B, int C, int D) {
            int length = 0, wide = 0;
            double t1 = (double)A * (double)C, t2 = (double)B * (double)D;
            if(t1 >= 0) 
                length = Math.abs(Math.abs(A) - Math.abs(C));
            else
                length = Math.abs(A) + Math.abs(C);
            if(t2 >= 0) 
                wide = Math.abs(Math.abs(B) - Math.abs(D));
            else
                wide = Math.abs(B) + Math.abs(D);
            return length * wide;    
        }
    
    }
  • 相关阅读:
    [Android实例] 同一Activity的实例被多次重复创建
    js 只能输入数字和小数点的文本框改进版
    DDMS文件权限设置
    form search 带参数 提交
    Jquery-UI dialog与ZeroClipboard 冲突问题的解决
    ZeroClipboard实现跨浏览器复制
    WebSocket使用80端口的方法
    Leetcode题目:First Bad Version
    Leetcode题目:Longest Common Prefix
    Leetcode题目:Counting Bits
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4887171.html
Copyright © 2020-2023  润新知