【刷题-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.

【刷题-LeetCode】223. Rectangle Area

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);
}
};
上一篇:java.util.ResourceBundle使用详解(转)


下一篇:C语言第一节 C语言程序与开发工具