LeetCode/solutions/223. Rectangle Area.md
2019-09-19 23:26:51 +08:00

21 lines
942 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [223. Rectangle Area](https://leetcode.com/problems/rectangle-area/)
# 思路
给定两个矩形的位置信息,求两个矩形并集区域面积。
基本思路:先直接将两个矩形面积相加,然后再判断是否有交集,若有则需要减去交集区域面积。
> 注意: 虽然题目说了最终结果不会超过int型但是不代表中间结果两矩形面积相加不会超过所以我们可以转成long long或者注意运算顺序
# C++
``` C++
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
// 不直接加起来是为了防止溢出
int area1 = (C - A) * (D - B), area2 = (H - F) * (G - E);
if (E >= C || F >= D || B >= H || A >= G) return area1 + area2;
// 先减后加是也为了防止溢出
return area1 - ((min(G, C) - max(A, E)) * (min(D, H) - max(B, F))) + area2;
}
};
```