Rectangle Area -- leetcode
2015-09-10 17:02
232 查看
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.
![](https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum possible value of
int.
基本思路:
两个矩形分别求和,再减去重叠部分。
计算重叠部分面积规律为:
下限求最大值,上限求最小值。具体为
1. left 取两个矩形left的最大值。 right取两者right最小值。
2. top和bottom同理。
检查求出的上限是否大于下限,即left是否小于right,bottom是否于小于top。如果不是,则没有重叠部分。
上面代码可以简化一下为:
省去了判断上限是否大于上限。将重叠和不重叠彻底统一处理。
2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
![](https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum possible value of
int.
基本思路:
两个矩形分别求和,再减去重叠部分。
计算重叠部分面积规律为:
下限求最大值,上限求最小值。具体为
1. left 取两个矩形left的最大值。 right取两者right最小值。
2. top和bottom同理。
检查求出的上限是否大于下限,即left是否小于right,bottom是否于小于top。如果不是,则没有重叠部分。
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int ans = (C-A) * (D-B) + (G-E) * (H-F); int a = max(A, E); int b = max(B, F); int c = min(C, G); int d = min(D, H); if (a >= c || b >= d) return ans; return ans - (c-a) * (d-b); } };
上面代码可以简化一下为:
省去了判断上限是否大于上限。将重叠和不重叠彻底统一处理。
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int a = max(A, E); int b = max(B, F); int c = max(a, min(C, G)); int d = max(b, min(D, H)); return (C-A) * (D-B) + (G-E) * (H-F) - (c-a) * (d-b); } };
相关文章推荐
- HDU-3394 Railway
- ios开发系列之Core Graphics中的CGContext
- USB虚拟串口
- 断言(ASSERT)的用法
- 获取cell中的button在整个屏幕上的位置
- tomcat远程调试
- 编译openwrt官方不支持的路由型号固件——以WR720N为例
- 设置Intel 82579LM 抓Vlan tag报文
- HDOJ 3336 Count the string
- 谈k12教育的互联网思维
- 程序员面试、算法研究、编程艺术、红黑树、数据挖掘5大系列集锦
- POJ - 1797 Heavy Transportation(求“最大生成树”)
- Palindrome Number
- 关于oracle plsql数据库ORA-01480: STR 绑定值的结尾 Null 字符缺失 的问题解决办法。
- Nginx as service on CentOS 6.6
- 从头到尾详解Android Studio
- 使用意图链接活动
- CentOS系统中常用查看日志和命令
- Centos mysql 存入中文字符乱码
- C++函数的嵌套调用和递归调用学习教程