1. 程式人生 > >223. Rectangle Area

223. Rectangle Area

ase script linear AC out 是否 red plane tput

問題描述:

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.

技術分享圖片

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Note:

Assume that the total area is never beyond the maximum possible value of int.

解題思路:

兩個矩形可能重合,所以為兩個矩形面積減去重合面積即可。

註意判斷是否存在重合時,四個值都要進行比較。

重合矩形的左下角的x值為max(A,E) ,y為max(B,F)

右上角的x值為min(C,G) y 為 min(D,H)

代碼:

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area1 = (D-B)*(C-A);
        int area2 = (H-F)*(G-E);
        
int ret = area1+area2; if(E >= C || F >= D || G <= A || H <= B) return ret; int I=max(A,E); int J=min(C,G); int K=max(B,F); int L=min(D,H); ret -= (J-I)*(L-K); return ret; } };

223. Rectangle Area