1. 程式人生 > 實用技巧 >【刷題-LeetCode】223. Rectangle Area

【刷題-LeetCode】223. Rectangle Area

  1. 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.

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

.

計算公式為:S = 矩形1的面積 + 矩形2的面積 - 相交部分的面積

相交的寬 = 矩形1的寬 + 矩形2的寬 - 實際圖形的寬

相交的高計算類似

如果相交部分的高或者寬小於0,說明沒有相交

題目原本定義的int會溢位???????

typedef long long int LL;
class Solution {
public:
    LL computeArea(LL A, LL B, LL C, LL D, LL E, LL F, LL G, LL H) {
        LL S = (C-A)*(D-B) + (G-E)*(H-F);
        LL d = abs(C - A) + abs(G - E) - abs(max(G, C) - min(A, E));
        LL h = abs(D - B) + abs(H - F) - abs(max(D, H) - min(F, B));
        return S - (d > 0 && h > 0 ? d * h : 0);
    }
};