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.
分別給出兩個矩形的坐下與右上坐標,求出兩個矩形的總面積。
思路:
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;
}
}