LeetCode 223. Rectangle Area(两个矩形的复合面积计算)

来源:互联网 发布:php row 编辑:程序博客网 时间:2024/05/16 08:01

原题网址:https://leetcode.com/problems/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 class Solution {    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        int sum = (C-A)*(D-B)+(G-E)*(H-F);        if (A<E) A=E;        else if (E<A) E=A;        if (A>=C || E>=G) return sum;        if (G>C) G=C;        else if (C>G) C=G;        if (A>=C || E>=G) return sum;        if (B<F) B=F;        else if (F<B) F=B;        if (B>=D || F>=H) return sum;        if (D>H) D=H;        else if (H>D) H=D;        if (B>=D || F>=H) return sum;        return sum-(C-A)*(D-B);    }}
可以对上面代码进行简化:

public class Solution {    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        return (int)((C-A)*(D-B)+(G-E)*(H-F)-Math.max(0, (long)Math.min(C,G)-Math.max(A,E))*Math.max(0,(long)Math.min(D,H)-Math.max(B,F)));    }}


0 0
原创粉丝点击