mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 223. Rectangle Area.md
This commit is contained in:
parent
5b8281645d
commit
91d85280a2
20
solutions/223. Rectangle Area.md
Normal file
20
solutions/223. Rectangle Area.md
Normal file
@ -0,0 +1,20 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user