LeetCode -- Rectangle Area

来源:互联网 发布:idg 知乎 编辑:程序博客网 时间:2024/05/01 20:37
题目描述:


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.




分别给出两个矩形的坐下与右上坐标,求出两个矩形的总面积。


思路:
1. 如果矩形不相交,总面积就是两个矩形面积和
2. 如果矩形相交,总面积就是两个矩形面积-相交部分面积。
矩形是否相交:设(A,B) (C,D)分别代表矩形1的左下与右上点坐标, (E,F) (G,H)分别为矩形2的左下与右上点坐标,不相交的情况为,D <=F , C<=E , G <= A, H <=B
求相交面积:将x坐标排序,取出中间两个并求差的绝对值得到deltaX;同理,将y坐标排序,取出中间两个,求差的绝对值得到deltaY,故s = deltaX * deltaY。




实现代码:



public class Solution {    public int ComputeArea(int A, int B, int C, int D, int E, int F, int G, int H) {                var sq1 = Math.Abs(A-C) * Math.Abs(B-D);    var sq2 = Math.Abs(E-G) * Math.Abs(F-H);        int common = 0;        if(D<=F || C<=E || G <=A || H <=B){    common = 0;    }    else{    var xArr = new int[]{A,E,C,G}.OrderBy(x=>x).ToList();    var yArr = new int[]{B,F,D,H}.OrderBy(y=>y).ToList();        common = Math.Abs(xArr[1] - xArr[2]) * Math.Abs(yArr[1] - yArr[2]);    }        return sq1 + sq2 - common;    }}


1 0
原创粉丝点击